您的位置 首页 技术

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

从v5.4.12开始,Laravel Collections现在包括一个when方法,允许您对项目执行条件操作,而不会中断链。 推荐:laravel教程 像所有其他Laravel …

从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方法详解的详细内容,更多请关注24课堂在线网其它相关文章!

本文来自网络,不代表24小时课堂在线立场,转载请注明出处:https://www.24ketang.cn/58315.html

为您推荐

返回顶部