您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

关于laravel5.4.12新增集合操作when方法详解

2024/6/1 2:39:09发布48次查看
从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
以上就是关于laravel5.4.12新增集合操作when方法详解的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product