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

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

Laravel 5

The unless method is the logical opposite of the when method. The unless method will execute the provided $callback on the collection; if the provided $value evaluates to false. A $default callback may also be supplied if the provided $value evaluates to true. Both of the provided callbacks will receive the current collection instance as their only argument; the unless 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 unless(
    $value,
    callable $callback,
    callable $default = null
);

Example Use

In the following example, we implement an example similar to the example in the when section. Like in the when section, we are supplying arguments for both the $callback and $default parameters as well as returning a reference to the collection within our callback functions:

$collection = collect([]);

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

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

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

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

    return $collection;
});

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

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

Start the Discussion

Leave a comment

Subscribe to our newsletter