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

47 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.

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 Cursor Vs Laravel Chunk 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