Use Cursor In Eloquent Query To Reduce Memory In Laravel

Do you know Laravel has a cursor method to reduce your memory size. The cursor method allows us to loop through your database records using a cursor, which will only runs a single query. When we need to process large amounts of data, the cursor method may be used to greatly reduce your memory usage


foreach (Flight::where('foo', 'bar')->cursor() as $flight) {


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

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

foreach ($users as $user) {
    echo $user->id;


Recommended : Use toBase in Eloquent to Reduce Memory in Laravel


Hope it can help you.


#laravel #eloquent-tips