Laravel Collections – each() Method

Laravel Collection - each() Method

Laravel Collection provides a fluent, convenient wrapper for working with arrays. In this post, we will learn about each() method method to iterate through and perform some actions items in the collection.

The Illuminate\Support\Collection class provides a fluent, convenient wrapper for working with arrays of data.

each() Method

The each() method of Laravel Collection takes a callback function and perform it on each item of the collection. If the callback function return false, then each() method breaks it’s iteration and return the reference to the original collection. In the callback function we define both an $item and a $key parameter.

The each method of Laravel’s Collection is identical to the native PHP for each loop.

Signature

The signature of each() method in the Illuminate/Support/Collection class looks something like below.

/**
 * Execute a callback over each item.
 *
 * @param  callable  $callback
 * @return $this
 */
public function each(callable $callback)
{
    //
}

Example

Here is a very basic example of the each() method, in which we will iterate through and print the name of cities.

use Illuminate\Support\Collection;

$cities = new Collection([
    'London', 'Paris', 'New York', 'Toranto', 'Tokyo'
]);

$cities->each(function($item, $key) {
    // Print each city name
    echo $item;
});

If you want to break the loop on a given condition, you can do something like below.

$cities->each(function($item, $key) {
    if ($item == 'Paris') {
        return false;
    }
    echo $item;
});

Above code example, will only print the “London”.

Laravel Eloquent returns the results as a Laravel Collection, so we can use this method to loop through on the results, instead of using the native foreach loop of PHP.

Your little help will keep this site alive and help us to produce quality content for you.