In this laravel tutorial, we will discuss the chunk and cursor method in an eloquent model with example. what is the difference between chunk and cursor method with hindi video.
Laravel eloquent chunk vs cursor method
- chunk()
- cursor()
Laravel eloquent chunk() method
When our website process more than thousand of data then server memory out and data not process. Laravel chunk method retrieved a bit of data. The chunk method returns only some data at a time. Thus chunk method reduces the memory uses and working with thousands of data. Let an example of chunk method
Chunk method first argument pass number of records that are received once than again next same number of records received this process run until all data, not process. Let an example of chunk method
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\Student; class StudentController extends Controller{ public function updateCreate(){ Student::chunk(200, function ($students) { foreach ($students as $student) { //do some data update operation here } }); } }
Laravel eloquent cursor() method
Laravel cursor method also works on memory reduction and operates on thousands of data. The cursor method greatly reduces your memory consumption. When processing a large amount of data than cursor method use. The cursor method runs a single query for large data. This method paginate. Chunk method easily paginates your query. Let an example of the cursor method.
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\Student; class StudentController extends Controller{ public function updateCreate(){ $students = Student::cursor()->filter(function ($student) { return $student->id > 500; }); foreach ($students as $student) { echo $student->id; } } }
You read this tutorial on advanced web tutorial. here we provide laravel beginners to advanced laravel tutorial.
Anmol Sharma
I am a software engineer and have experience in web development technologies like php, Laravel, Codeigniter, javascript, jquery, bootstrap and I like to share my deep knowledge by these blogs.
Related tutorial links
- What is laravel eloquent model and introduction
- part 1 laravel eloquent model all configuration hindi
- part 2 laravel insert and create data by eloquent model tutorial
- part 3 laravel data retrieve method
- part 4 first, find, findOrFail and firstOrFail method
- part 5 laravel delete vs truncate method
- part 6 laravel save vs update method
- part 7 laravel updateOrCreate and upsert
- part 8 laravel chunk vs cursor method
- part 9 laravel eloquent subquery select
- part 10 laravel findOrFail vs firstOrFail
- part 11 laravel create and retrieve data
- part 12 laravel eloquent aggregate functions
- part 13 laravel isDirty vs isClean vs wasChanged method