Laravel Collections – each() Method

Laravel Collection - each() Method

Laravel Collections ( 8 Lessons )

Laravel Collections is one of the most powerful features of Laravel. Basically, collections are PHP arrays but it’s an Object Oriented approach to deal with PHP arrays.

see full series
  1. Laravel Collections – Introduction to Collections
  2. Laravel Collections – make Method
  3. Laravel Collections – wrap() and unwrap() Methods
  4. Laravel Collections – map() Method
  5. Laravel Collections – times() Method
  6. Laravel Collections – collapse() Method
  7. Laravel Collections – contains() & containsStrict() Methods
  8. Laravel Collections – each() Method

In this post, we will learn how to use Laravel Collections each() method to iterate through and perform some actions items in the collection.

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 foreach 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 return 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.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

*
*

This site uses Akismet to reduce spam. Learn how your comment data is processed.