How to use each function in Laravel

How to use each function in Laravel

Posted on:August 22, 2019 at 10:00 AM

Laravel has a beautiful each method that can help you to process a lot of models. Consider that, you have thousands of models, so, don’t load them all into memory, but chunk them. Laravel each function will help you to figure out in this issue. Let’s see how to use each function in Laravel.

What is exactly each method?

According to the documentation-

The each method iterates over the items in the collection and passes each item to a callback:

$collection->each(function ($item, $key) {
    //
});

Real life scenario

Imagine that, you have a user model where you have more than a hundred thousand records. Now you want to concatenate the first name and last name then want to implement uppercase on that. Here is an example of how to do that using each().

$users = User::all();

$users->each(function ($item, $key) {
	$fullName = $item['first_name'] . ' ' . $item['last_name'];

	return strtoupper($fullName);
});

dd($users);

The each function will iterate over the users collection. Firstly it will concatenate first_name and last_name and then return by making upercase of the full name.

If you would like to stop iterating through the items, you may return false from your callback:


$collection->each(function ($item, $key) {
    if (/* some condition */) {
        return false;
    }
});

You can get the Laravel code here