Lazy Collections

What are Lazy Collections?

Lazy Collections in Laravel provide a memory-efficient way to work with large datasets by processing data one item at a time. They are especially useful for handling streams of data or iterating over large Eloquent queries without loading everything into memory.


Origin

Lazy Collections were introduced in Laravel 6, leveraging PHP Generators to enable on-demand processing of data, reducing memory usage in high-load scenarios.


Why are they important?

  1. Memory Efficiency: Reduces memory consumption by processing data incrementally.
  2. Handles Large Datasets: Works seamlessly with large datasets that cannot fit into memory.
  3. Improves Performance: Minimizes the overhead of loading unnecessary data.

Best Practices

  1. Use for Large Queries: Apply lazy collections to Eloquent queries with thousands of records.
  2. Combine with Generators: Write custom generators to produce data streams.
  3. Avoid Complex Transformations: Keep operations lightweight to maintain efficiency.

Example in Action

Using Lazy Collections to process a large dataset:

use Illuminate\Support\LazyCollection;

LazyCollection::make(function () {
    for ($i = 0; $i < 1000000; $i++) {
        yield $i;
    }
})->each(function ($value) {
    echo $value;
});

Lazy Collections with Eloquent:

User::cursor()->each(function ($user) {
    echo $user->name;
});

This approach processes one user at a time, conserving memory and improving performance for large datasets.