Home / Snippets / Laravel Query Cursor Code Example
Laravel Query Cursor Code Example cover

Laravel Query Cursor Code Example

809

3 years ago

0 comments

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

Alaz

Week-end developer currently experimenting with web, mobile, and all things programming.

Topics:

Frontend

Resource

Average

Average

Support Us

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

Welcome to PostSrc V3

PostSrc Dark Logo

You have to login to favorite this