Home  >  Article  >  PHP Framework  >  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

藏色散人
藏色散人forward
2020-04-06 11:50:482009browse

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],
];

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'];
    });
}

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'];
        });
    });

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!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete