Posts Learn Components Snippets Categories Tags Tools About
/

Laravel Cursor Vs Laravel Chunk Code Example

Learn how to optimise retrieving data with Laravel cursor and Laravel chunk for better performance

Created on Jul 23, 2021

1136 views

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.

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

Load comments for Laravel Cursor Vs Laravel Chunk Code Example

)