
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 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],
];
Previously to filter based on a query string you might do 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'];
});
});
Filed in: Laravel 5.4 / Collections
Enjoy this? Get Laravel News delivered straight to your inbox every Sunday.
No Spam, ever. We'll never share your email address and you can opt out at any time.
Newsletter

Join the weekly newsletter and never miss out on new tips, tutorials, and more.
Laravel Jobs

- Laravel Developer
-
San Jose, CA - Must Be Local
X3 Builders - Experienced PHP Developer
-
Wilmington, NC
Queensboro Shirt Company - Senior Laravel developer
-
Netherlands, Rotterdam
Pionect - Senior Laravel Engineer
-
Remote okay (must already live in USA)
Hawthorne Effect - Senior Software Engineer (Remote - Contract)
-
Remote
Koodi Systems - PHP Developer
-
Pittsburgh / Remote
Sequoia Waste Solutions - Software Developer
-
Eindhoven
Simac IDS
Handling Conflict: How to Talk to Your Coworker
Turning Conflict to Conversation Conflict is a natural part of any relationship, especially those people we spend the…
Request Object Changes in Lumen 5.4
A couple of weeks ago the Lumen core team managed to fix an issue with the request object when being called in unit t…