Posts Learn Components Snippets Categories Tags 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

13 views

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;
  });

Snippets by

PostSrc poster

PostSrc

Full stack developer mainly focusing on the front end side of the web. The main author of PostSrc and loves writing tutorial and guides online.

Load comments for Laravel Query Cursor Code Example

new

PostSrc Code Components

Collection of Tailwind CSS components for everyone to use. Browse all of the components that's right for your project.

View Components

Other Code Snippets

More