Lazy Collection

Laravel Eloquent ORM Lazy Collection

Explain the difference between Eloquent::get() and Eloquent::lazy()

When you run the Eloquent function and get the data from the database by using get() method. It will immediately get all the data from the database, transform the data to the eloquent object and save all the transformed eloquent object data to the memory. It will use a lot of memory.

If we need to process the data then it will traverse the whole data with foreach again.

// Get all data and transform it to the eloquent model
$UserCollection = UserModel::where("{$user_table}.status", $user_status)->get();

foreach($UserCollection as $User) {
    // Process the eloquent data again
}

We can use the lazy() method to keep the original query and run it when we REALLY NEED IT to reduce the memory usage

// Keep the query but haven't run the query to get the data yet
$UserLazyCollection = UserModel::where("{$user_table}.status", $user_status)->lazy();

foreach($UserLazyCollection as $User) {
    // Run the query and transform data to the eloquent model right here
}

Example

Eloquent Left Join Lazy Collection

$user_table = (new UserModel)->getTable();
$comment_table = (new CommentModel)->getTable();
$comment_status = 'enable';
$user_status = 'enable';

$UserCommentLazyCollection = UserModel::select(['*'])
    ->leftJoin($comment_table, function($JoinSubQuery) use (
        $comment_table,
        $user_table,
        $comment_status,
    ) {
        $JoinSubQuery->on("{$user_table}.id", "{$comment_table}.user_id")
            ->where("{$comment_table}.status", $comment_status);
    })
    ->where("{$user_table}.status", $user_status);
    ->lazy();


foreach($UserCommentLazyCollection as $UserComment) {
    // It will run the query and get the data to the memory one by one record
}

Reference