從v5.4.12開始,Laravel Collections現在包括一個when方法,允許您對專案執行條件操作,而不會中斷鏈,
像所有其他Laravel 集合方法,這一個可以有很多用例,選擇其中一個例子,想到的是能夠基于查詢字串引數進行過濾,
為了演示這個例子,讓我們假設我們有一個來自Laravel News Podcast的主機串列:
$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],
];
舊版本要根據查詢字串進行過濾,您可能會這樣做:
$inUsa = collect($hosts)->where('location', 'USA');
if (request('retired')) {
$inUsa = $inUsa->filter(function($employee){
return ! $employee['is_active'];
});
}
使用新when方法,您現在可以在一個鏈式操作中執行此操作:
$inUsa = collect($hosts)
->where('location', 'USA')
->when(request('retired'), function($collection) {
return $collection->reject(function($employee){
return $employee['is_active'];
});
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/63436.html
標籤:PHP
上一篇:PHP trim()函式詳解
下一篇:PHP面向物件的相關概念
