关于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 分享