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.
Leave a reply