How to chunk results from a custom query in Laravel?


If your database table has lots of data, chunk() method is the best to use. The chunk() method can be used on the DB facade and also on Eloquent models.

The chunk() takes care of fetching a small amount of data at a time and the result is present inside the closure for processing.

Consider the following users table that has 1000 records in it. We are going to make use of chunk() to retrieve 100 records at a time.

Example 1

<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\DB; class UserController extends Controller { public function index() { DB::table('users')->orderBy('id')->chunk(100, function ($users) { foreach ($users as $user) { echo $user->id."=>".$user->name." "; } }); } }

To use DB facade, include the class Illuminate\Support\Facades\DB;

In above example chunk() will take care of getting 100 records at a time and use inside foreach(). It will process till all the records are fetched in a batch of 100.

Output

The output for above is −

Example 2

In case you want to stop from processing, you can do so as shown below −

<?php namespace App\Http\Controllers; use Illuminate\Http\Request; //use App\Models\User; use Illuminate\Support\Facades\DB; class UserController extends Controller{ public function index() { DB::table('users')->orderBy('id')->chunk(100, function ($users) { foreach ($users as $user) { echo $user->id."=>".$user->name." "; if ($user->id == 150) { return false; } } }); } }

You can return false on a condition where you don’t want the chunk() to process any further.

Output

The output of the above is as follows −

Example 3

Using chunk() on Eloquent User model −

<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\User; //use Illuminate\Support\Facades\DB; class UserController extends Controller{ public function index() { User::orderBy('id')->chunk(100, function ($users) { foreach ($users as $user) { echo $user->id."=>".$user->name." "; } }); } }

Output

The output of the above code is −

Example 4

Using chunk() on Eloquent model

<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\User; class UserController extends Controller{ public function index() { $users = User::all(); $chunkedUsers = $users->chunk(10); foreach ($chunkedUsers as $records) { foreach($records as $user) { echo $user->id."=>".$user->name.""; } } } }

Output

The output of the above code is −

Updated on: 30-Aug-2022

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements