Search

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

April 22, 2018 —John Koster

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

1public function unless(
2 $value,
3 callable $callback,
4 callable $default = null
5);

#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:

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

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!

Some absolutely amazing
people

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.