Laravel - Getting Started - Cursors

Similar to the lazy method, the cursor method may be used to significantly reduce your application's memory consumption when iterating through tens of thousands of Eloquent model records.

The cursor method will only execute a single database query; however, the individual Eloquent models will not be hydrated until they are actually iterated over. Therefore, only one Eloquent model is kept in memory at any given time while iterating over the cursor.

Since the cursor method only ever holds a single Eloquent model in memory at a time, it cannot eager load relationships. If you need to eager load relationships, consider using the lazy method instead.

Internally, the cursor method uses PHP generators to implement this functionality:

    
    use App\Models\Flight;
    
    foreach (Flight::where('destination', 'Zurich')->cursor() as $flight) {
        //
    }
	

The cursor returns an Illuminate\Support\LazyCollection instance. Lazy collections allow you to use many of the collection methods available on typical Laravel collections while only loading a single model into memory at a time:

    
    use App\Models\User;
    
    $users = User::cursor()->filter(function ($user) {
        return $user->id > 500;
    });
    
    foreach ($users as $user) {
        echo $user->id;
    }
	

Although the cursor method uses far less memory than a regular query (by only holding a single Eloquent model in memory at a time), it will still eventually run out of memory. This is due to PHP's PDO driver internally caching all raw query results in its buffer. If you're dealing with a very large number of Eloquent records, consider using the lazy method instead.