How to update thousands of data in a database in laravel than a solution in this tutorial. We use chunk method to perform an operation on thousands of data.
Laravel query builder chunk method.
Laravel provide a chunk method for perform operation on big data with.If we perform an update operation on big data then our server fails but thank god laravel provide a chunk method.
This method gets a small chunk result at a time. Mean when we want to update thousand of data with then it divides data into small chunks like one time retrieve only a hundred data then again next hundred data. More explain in below example
Example 1 get simple data in chunk
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; class StudentController extends Controller{ public function index(){ $students = DB::table('students')->orderBy('id')->chunk(100, function($users) { foreach ($users as $user) { // perform some operation here echo $user->name; } }); } }
Example 2 update data
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; class StudentController extends Controller{ public function index(){ $students = DB::table('students')->chunk(100, function($users) { foreach ($users as $user) { // perform some operation here DB::table('students') ->where('id', $user->id) ->update(['status' => '1']); } }); } }
You read this tutorial on advanced web tuts. here we provide beginners to advanced 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
- laravel query builder introduction tutorial
- part 1 laravel query insert data
- part 2 laravel all type of where conditions in query builder
- part 3 laravel whereDate, whereYear and whereTime qyery method
- part 4 compare two db columns in laravel query builder
- part 6 laravel pluck method get single column value
- part 7 laravel select and addselect query in query builder
- part 5 laravel first and find queries
- part 8 laravel edit and update method query explaination
- Part 9 laravel query for update or insert data by one method
- part 10 laravel delete vs truncate vs drop method
- part 11 gropupby and orderby query tutorial
- Part 12 laravel union of two queries
- part 13 laravel all aggregate functions with example
- part 14 laravel query builder chunk method
- part 15 laravel exists() and doesntExist() method
- part 16 laravel paginate vs simplePaginate method
- part 17 laravel all join methods