Reduce Memory Usage in Laravel Using lazyById()

Process and update large datasets safely without loading everything into memory.

  • 30 May, 2026
  • 24 Views

Reduce Memory Usage in Laravel Using lazyById()

Laravel provides a cleaner approach:

lazyById()

Basic Usage

User::lazyById()->each(function ($user) {
    // Process user
});

Instead of loading all users into memory, Laravel fetches records incrementally.


Real Project Example

Imagine you need to recalculate reward points for every customer:

User::where('is_active', true)
    ->lazyById()
    ->each(function ($user) {
        $user->update([
            'reward_points' => $user->orders()->sum('points')
        ]);
    });

This can safely process tens of thousands of records.


Why Not Just Use lazy()?

Many developers use:

User::lazy()

But if you're updating records while iterating, lazyById() is safer because it uses:

WHERE id > previous_id

instead of relying on offsets.

This prevents:

  • Missing records
  • Duplicate processing
  • Pagination shifting issues

Why This Is Useful

It helps you:

  • Process huge datasets
  • Keep memory usage low
  • Safely update records during iteration
  • Build scalable console commands and jobs

When to Use It

Use lazyById() when:

  • Processing more than a few thousand records
  • Updating records while looping
  • Running scheduled maintenance jobs
  • Building import/export tools


Share: