PASSWORD RESET

Your destination for complete Tech news

What is Lazy collection in Laravel?

478 0
< 1 min read

In Laravel, a Lazy Collection is a collection that defers its processing until the data is actually needed. This can be useful for working with large datasets, as it allows you to process the data in a more memory-efficient way.

A Lazy Collection is created by calling the LazyCollection::make method and passing it a callback function that returns an iterator. The callback function will be executed when the data is needed, and the iterator will be used to retrieve the data from the callback.

Here’s an example of how you can use a Lazy Collection to process a large dataset:

$users = LazyCollection::make(function () {
    $handle = fopen('users.csv', 'r');

    while ($row = fgetcsv($handle)) {
        yield $row;
    }
});

$users->filter(function ($user) {
    return $user['age'] > 18;
})->each(function ($user) {
    // Process the user
});

In the example above, the LazyCollection::make method creates a Lazy Collection that reads the data from the users.csv file one row at a time. The filter method filters the collection to include only users with an age greater than 18, and the each method processes each user in the filtered collection.

Since the Lazy Collection defers its processing until the data is actually needed, the entire dataset is not loaded into memory at once. This can be more memory-efficient than loading the entire dataset into a regular Collection and then filtering and processing it.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.