Use lazy() for Memory-Friendly Collection Processing in Laravel

Category : Laravel Performance Tips Publish At : 02 Oct, 2025

Share On :

When dealing with thousands (or even millions) of records, loading them all into memory with all() or get() can slow down your app or even crash it. Laravel solves this problem with lazy(), a memory-efficient way to process records in chunks.

The Risky Way – Using all()

$users = User::all();
foreach ($users as $user) {
    // process each user
}

This loads every single row into memory at once. If you have 1 million users, your server might not survive.

The Laravel Way – Using lazy()

User::lazy()->each(function ($user) {
    // process each user without loading everything into memory
});

Instead of loading everything, lazy() fetches records in small chunks under the hood and streams them one by one.

Real-World Example

Imagine you want to send a notification to every user in the database:

User::lazy()->each(function ($user) {
    $user->notify(new ImportantUpdateNotification());
});

Even if you have millions of users, your memory usage stays low and predictable.