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

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

Laravel 5

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.

Signature

public function when(
    $value,
    callable $callback,
    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.

$collection = collect([]);

// The `$callback` callback will be invoked.
$collection->when(true, function ($collection) {
    $collection->push('Pushed the truth message!');

    return $collection;
}, function ($collection) {
    $collection->push('Pushed the default message!');

    return $collection;
})
// The `$default` callback will be invoked.
->when(false, function ($collection) {
    $collection->push('Pushed the truth message!');

    return $collection;
}, function ($collection) {
    $collection->push('Pushed the default message!');

    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!

Start the Discussion

Leave a comment

Subscribe to our newsletter