Home > PHP Framework > Laravel > Detailed explanation of the new collection operation when method in laravel5.4.12

Detailed explanation of the new collection operation when method in laravel5.4.12

藏色散人
Release: 2020-04-06 11:50:48
forward
2109 people have browsed it

Starting with v5.4.12, Laravel Collections now include a when method that allows you to perform conditional actions on items without breaking the chain.

Recommended: laravel tutorial

Like all other Laravel collection methods, this one can have many use cases, choose one of the examples that comes to mind is to be able to based on query string parameters to filter.

To demonstrate this example, let's assume we have a list of hosts from the 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],
];
Copy after login

Older versions To filter based on the query string, you might do this:

$inUsa = collect($hosts)->where('location', 'USA');
if (request('retired')) {
    $inUsa = $inUsa->filter(function($employee){
        return ! $employee['is_active'];
    });
}
Copy after login

Using the new when method, you can now perform this operation in a chain operation:

$inUsa = collect($hosts)
    ->where('location', 'USA')
    ->when(request('retired'), function($collection) {
        return $collection->reject(function($employee){
            return $employee['is_active'];
        });
    });
Copy after login

Translated from laravel news, original link https://laravel-news.com/laravel-collections -when-method

The above is the detailed content of Detailed explanation of the new collection operation when method in laravel5.4.12. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template