Laravel Collections – each() Method

Laravel Collection - each() Method

Laravel Collections ( 11 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
  9. Laravel Collection – Using toJson() Method
  10. Laravel Collection – Filtering Collection Items using where()
  11. Laravel Collection – Using splice() Method to Remove Items

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.