Posts Learn Components Snippets Categories Tags Tools About

Laravel Query Cursor Code Example

Speed up Laravel query by using cursor method to reduce application memory consumption when iterating through thousands of model records

Created on Jul 23, 2021


You can easily implement PHP generators when querying an eloquent model with the help of "cursor" method. By using Laravel Cursor to query those models, it will greatly reduce the amount of memory since only one eloquent model is located at a time.

Do note that you can't eager load a relationship with "Laravel cursor" but instead you will have to use the "lazy" method.

Laravel Query Cursor Example
use App\Models\Posts;

foreach (Posts::where('published', true)->cursor() as $post) {
    // do whatever you want with the $post

By default "cursor" returns Laravel LazyCollection and like normal Laravel Collection, you can use pretty much any of the available methods available.
use App\Models\Post;

$users = Post::cursor()
  ->filter(function ($post) {
    return $post->id > 100;
  })->each(function ($post) {
    echo $post->id;

If you like our tutorial, do make sure to support us by being our Patreon or buy us some coffee ☕️

Load comments for Laravel Query Cursor Code Example