Laravel each(): Execute function on all Collection items

By Parth Patel on Oct 10, 2020

Laravel Collections has lot of helper methods among which one we will talk about is each() method.

The each() method is used to pass callback function to operate on all the items in collection. Pretty simple right?

Moreover, if you want to break the loop, simple! Just return false in the callback function. When the callback function returns false, each() method will stop iterating and will simply return the original collection.

Let's review some examples:

Example

Let's checkout one very simple example where each() method is being called on the collection object with callback function passed.

use Illuminate\Support\Collection;

$users = new Collection([
    'John','Dave','Hugh','Pete'
]);

// JohnDaveHughPete
$users->each(function($user, $key) {
    echo $user;
});

Let's checkout an example where we break the function iteration early by returning false.

use Illuminate\Support\Collection;

$users = new Collection([
    'John','Dave','Hugh','Pete'
]);

// John
$collection->each(function($item, $key) {
    if ($item == 'Dave') {
        return false;
    }

    echo $item;
});

So, this is quick review on how to iterate each item in Laravel Collection via each() method. This method can also be used on Eloquent Collection object.