從v5.4.12開始,Laravel Collections現(xiàn)在包括一個(gè)when方法,允許您對(duì)項(xiàng)目執(zhí)行條件操作,而不會(huì)中斷鏈。
推薦:laravel教程
像所有其他Laravel 集合方法,這一個(gè)可以有很多用例,選擇其中一個(gè)例子,想到的是能夠基于查詢字符串參數(shù)進(jìn)行過濾。
為了演示這個(gè)例子,讓我們假設(shè)我們有一個(gè)來自Laravel News Podcast的主機(jī)列表:
$hosts = [ ['name' => 'Eric Barnes', 'location' => 'USA', 'is_active' => 0], ['name' => 'Jack Fruh', 'location' => 'USA', 'is_active' => 0], ['name' => 'Jacob Bennett', 'location' => 'USA', 'is_active' => 1], ['name' => 'Michael Dyrynda', 'location' => 'AU', 'is_active' => 1], ];
舊版本要根據(jù)查詢字符串進(jìn)行過濾,您可能會(huì)這樣做:
$inUsa = collect($hosts)->where('location', 'USA'); if (request('retired')) { $inUsa = $inUsa->filter(function($employee){ return ! $employee['is_active']; }); }
使用新when方法,您現(xiàn)在可以在一個(gè)鏈?zhǔn)讲僮髦袌?zhí)行此操作:
$inUsa = collect($hosts) ->where('location', 'USA') ->when(request('retired'), function($collection) { return $collection->reject(function($employee){ return $employee['is_active']; }); });
翻譯自laravel news,原文鏈接 https://laravel-news.com/laravel-collections-when-method