laravel chunk query example; In this tutorial you will learn how to use chunk method with large records in laravel.
Basically, Laravel eloquent chunk method break the large group of data set into smaller group of data set (chunks). If you need to work with thousands of database records, consider using the chunk
method provided by the DB
facade.
Laravel chunk method retrieves a small chunk of results at a time and feeds each chunk into a closure for processing. For example, let’s retrieve the entire users table in chunks of 100 records at a time.
Let’s understand laravel chunk method through examples:
Example 1:
use App\Models\User;
class UserController extends Controller
{
public function index()
{
$users = User::all()->chunk(100);
dd($users);
}
}
Example 2:
In Controller:
use App\Models\User;
class UserController extends Controller
{
public function index()
{
$users = User::all();
return view('users',compact('users'));
}
}
In Blade File:
@foreach($users->chunk(100) as $row)
{{ $row }}
@endforeach
Example 3:
use App\Models\User;
class UserController extends Controller
{
public function index()
{
User::orderBy('id')->chunk(100, function ($users) {
foreach ($users as $user) {
//
}
});
}
}
Example 4:
You may stop further chunks from being processed by returning false
from the closure:
use App\Models\User;
class UserController extends Controller
{
public function index()
{
User::orderBy('id')->chunk(100, function ($users) {
// Process the records...
return false;
});
}
}
Example 5:
If you are updating database records while chunking results, your chunk results could change in unexpected ways. If you plan to update the retrieved records while chunking, it is always best to use the chunkById
method instead. This method will automatically paginate the results based on the record’s primary key:
use App\Models\User;
class UserController extends Controller
{
public function index()
{
User::where('active', false)
->chunkById(100, function ($users) {
foreach ($users as $user) {
DB::table('users')
->where('id', $user->id)
->update(['active' => true]);
}
});
}
}
I hope this will help you..