Laravel Collections – 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- Laravel Collections – Introduction to Collections
- Laravel Collections – make Method
- Laravel Collections – wrap() and unwrap() Methods
- Laravel Collections – map() Method
- Laravel Collections – times() Method
- Laravel Collections – collapse() Method
- Laravel Collections – contains() & containsStrict() Methods
- Laravel Collections – each() Method
- Laravel Collection – Using toJson() Method
- Laravel Collection – Filtering Collection Items using where()
- 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.