Search

Laravel 5 Collections: Executing a Function On All Collection Elements With each

April 22, 2018 —John Koster

The each method accepts a $callback which will be called on each item in the collection. If the $callback returns false, the each method will break from its iterator and return a reference back to the original Collection instance. The callback should define both an $item and a $key parameter. For most use cases, the each method is functionally identical to PHP's foreach construct.

#Signature

1public function each(
2 callable $callback
3);

#Example Use

The following examples are trivial use cases of the each method in that we iterate each element of the collection and echo the element:

1use Illuminate\Support\Collection;
2 
3// Create a new collection instance.
4$collection = new Collection([
5 'first', 'second', 'third'
6]);
7 
8// firstsecondthird
9$collection->each(function($item, $key) {
10 echo $item;
11});
12 
13// Break out of the loop early. Will display
14// 'first' only.
15$collection->each(function($item, $key) {
16 if ($item == 'second') {
17 return false;
18 }
19 
20 echo $item;
21});

The each method does not explicitly allow the modification of a collection's items, and simply returns a reference to the original collection. However, because of the way PHP treats objects as references, it is possible to modify the properties of objects within a collection:

1use Illuminate\Support\Collection;
2 
3class User
4{
5 
6 /**
7 * A hypothetical user's first name.
8 *
9 * @var string
10 */
11 public $firstName = '';
12 
13 /**
14 * A hypothetical user's favorite number.
15 *
16 * @var integer
17 */
18 public $favoriteNumber = 0;
19 
20 public function __construct($firstName, $favoriteNumber)
21 {
22 $this->firstName = $firstName;
23 $this->favoriteNumber = $favoriteNumber;
24 }
25 
26}
27 
28// Create a new collection instance.
29$collection = new Collection([
30 new User('Jane', 7),
31 new User('Sarah', 9),
32 new User('Ben', 2)
33]);
34 
35// Change everyone's favorite number to 3.
36$collection->each(function($item, $key) {
37 $item->favoriteNumber = 3;
38});

After the above call to each, the $collection variable would contain a value similar to the following output:

1object(Illuminate\Support\Collection)
2 protected 'items' =>
3 array
4 0 =>
5 object(User)
6 public 'firstName' => string 'Jane'
7 public 'favoriteNumber' => int 3
8 1 =>
9 object(User)
10 public 'firstName' => string 'Sarah'
11 public 'favoriteNumber' => int 3
12 2 =>
13 object(User)
14 public 'firstName' => string 'Ben'
15 public 'favoriteNumber' => int 3

It should also be noted that the each method effects the original Collection instance and does not return a modified copy of the original Collection instance.

#Using each With Higher Order Messages

The each method can also be used with higher order messaging, which allows us to invoke collection methods and access properties on objects using PHP's property accessors syntax. In the following example, we will create modify our User class to define a method sendWelcomeEmail; this method would be used to send a welcome email to the user represented by the instance, but we will not implement this method in this example; instead, we will leave it empty to demonstrate higher order messages with the each method:

1class User
2{
3 
4 /**
5 * A hypothetical user's first name.
6 *
7 * @var string
8 */
9 public $firstName = '';
10 
11 /**
12 * A hypothetical user's favorite number.
13 *
14 * @var integer
15 */
16 public $favoriteNumber = 0;
17 
18 public function __construct($firstName, $favoriteNumber)
19 {
20 $this->firstName = $firstName;
21 $this->favoriteNumber = $favoriteNumber;
22 }
23 
24 public function sendWelcomeEmail()
25 {
26 // ...
27 }
28 
29}

Without higher order messages, we would typically have to write code like so:

1$collection = new Collection([
2 new User('Jane', 7),
3 new User('Sarah', 9),
4 new User('Ben', 2)
5]);
6 
7$collection->each(function ($user) {
8 $user->sendWelcomeEmail();
9});

With higher order messages, we can now re-write the previous example to the following:

1$collection = new Collection([
2 new User('Jane', 7),
3 new User('Sarah', 9),
4 new User('Ben', 2)
5]);
6 
7$collection->each->sendWelcomeEmail();

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.