Home / Snippets / Laravel Cursor Vs Laravel Chunk Code Example
Laravel Cursor Vs Laravel Chunk Code Example cover

Laravel Cursor Vs Laravel Chunk Code Example

1.1K

2 years ago

0 comments

To optimize retrieving data from the Laravel model, you can make use of either the "cursor" method or "chunk" method. By using these methods, you can significantly reduce your application memory consumption when iterating through thousands of Eloquent model records.

Laravel Cursor Code Example
When using the cursor method you will have to iterate the returned value in order to execute the code. You can refer to the code below to get more understanding.
<?php

use App\Models\Post;

$posts = Post::cursor(); // This is cursor instance... no data retireved yet

$post->each(fn ($post) => print($post->title)); // This will start printing the post title one by one

Laravel Chunk Code Example
When using chunk the result returned will be divided by the X number of chunks that you have specified. Imagine you have 1000 posts and you decide to chunk it for every 200 records, doing so will make the total number of 5 chunks.
<?php

use App\Models\Post;

Post::chunk(200, function ($posts) {
    dd(count($posts)); // total 200

    foreach ($posts as $post) {
        print($post->title);
    }
});

Pro tip:
In personal experience, it's recommended to use "cursor" more since it's more efficient. But do note that the performance gain is only visible if you have many records.
notion avatar

Ahabz

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