Laravel 5 Collections: Conditionally Executing a Callback On a Collection's Elements With when

April 22, 2018 —John Koster

The when method will execute the provided $callback on the collection if the provided boolean $value evaluates to true. A $default callback may also be supplied if the provided $value evaluates to false. Both of the provided callbacks will receive the current collection instance as their only argument; the when method has the potential to modify the original collection instance.

The when method will return a reference to the original collection instance.


1public function when(
2 $value,
3 callable $callback,
4 callable $default = null

#Example Use

The following example demonstrates the behavior of the when method. In both of the when calls we are supplying both the $callback and $default callbacks. Additionally, we are returning the collection instance within the callback functions to continue our method chain; this is because the when method will return the results of the callback.

1$collection = collect([]);
3// The `$callback` callback will be invoked.
4$collection->when(true, function ($collection) {
5 $collection->push('Pushed the truth message!');
7 return $collection;
8}, function ($collection) {
9 $collection->push('Pushed the default message!');
11 return $collection;
13// The `$default` callback will be invoked.
14->when(false, function ($collection) {
15 $collection->push('Pushed the truth message!');
17 return $collection;
18}, function ($collection) {
19 $collection->push('Pushed the default message!');
21 return $collection;

After the above code has executed, the $collection would contain the following values:

Index Value
0 Pushed the truth message!
1 Pushed the default message!

Some absolutely amazing

The following amazing people help support this site and my open source projects ♥️
If you're interesting in supporting my work and want to show up on this list, check out my GitHub Sponsors Profile.