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.


Facebook Github
A web enthusiastic, a self-motivated full-stack software engineer from Dhaka, Bangladesh with experience in developing applications using Laravel , React and Vue js