推荐: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
以上就是关于laravel5.4.12新增集合操作when方法详解的详细内容。
