Codementor Events

Laravel Collections “when” Method

Published Jul 08, 2017
Laravel Collections “when” Method

Laravel Collections “when” Method

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

Like all the other Laravel Collection methods this one can have a lot of use cases but one example that comes to mind is being able to filter based on a query string parameter.

To demonstrate that example, let’s pretend we have a list of hosts:

$hosts = [
    ['name' => 'Syed', 'location' => 'PAK', 'is_active' => 0],
    ['name' => 'Eric', 'location' => 'USA', 'is_active' => 0],
    ['name' => 'Carrie', 'location' => 'USA', 'is_active' => 1],
    ['name' => 'Mo Hu', 'location' => 'UK', 'is_active' => 1],
];

As you would have done this previously to filter based on a query string you might did something like this:

$inUsa = collect($hosts)->where('location', 'USA');

if (request('retired')) {
    $inUsa = $inUsa->filter(function($employee){
        return ! $employee['is_active'];
    });
}

With the new when method you can now do this all in one Collection chain:


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

I hope you liked it. 👍 if you like it, subs if you ❤️ it

✌

I am a codementor
Contact me on Codementor

Discover and read more posts from Syed Ikram Shah
get started
post commentsBe the first to share your opinion
Show more replies