Laravel Collections “when” Method

Tutorials

February 16th, 2017

collections-when.png

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 from the Laravel News Podcast:

1$hosts = [
2 ['name' => 'Eric Barnes', 'location' => 'USA', 'is_active' => 0],
3 ['name' => 'Jack Fruh', 'location' => 'USA', 'is_active' => 0],
4 ['name' => 'Jacob Bennett', 'location' => 'USA', 'is_active' => 1],
5 ['name' => 'Michael Dyrynda', 'location' => 'AU', 'is_active' => 1],
6];

Previously to filter based on a query string you might do something like this:

1$inUsa = collect($hosts)->where('location', 'USA');
2
3if (request('retired')) {
4 $inUsa = $inUsa->filter(function($employee){
5 return ! $employee['is_active'];
6 });
7}

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

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

Filed in:

Eric L. Barnes

Eric is the creator of Laravel News and has been covering Laravel since 2012.