關于laravel5.4.12新增集合操作when方法詳解

從v5.4.12開始,laravel collections現在包括一個when方法,允許您對項目執行條件操作,而不會中斷鏈。

推薦:laravel教程

像所有其他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']; ????????}); ????});

翻譯自laravel news,原文鏈接 https://laravel-news.com/laravel-collections-when-method

? 版權聲明
THE END
喜歡就支持一下吧
點贊15 分享