When dealing with lots of data, it is good practice to fetch in chunks from the database. This reduces lag in the application.
In this shot, we will learn how to fetch data from our database in chunks using the chunk()
method.
chunk()
method?The chunk()
method is part of the query builder that fetches data from the database in smaller numbers/amounts. This is suitable when you have thousands of records your application is working with.
DB::table('users')->orderBy('id')->chunk(100, function ($users) {
foreach ($users as $user) {
//
}
});
The chunk()
method accepts two parameters or arguments:
Chunk value: The number of records you want to fetch at a time.
The Callback function.
use Illuminate\Support\Facades\DB;
DB::table('posts')->orderBy('id')->chunk(50, function ($posts) {
foreach ($posts as $post) {
echo $post->title;
}
});
From the code example above, we fetch in chunks of fifty records (50). We pass a callback function to iterate through the $posts
, after which we echo the $post->title
.
Depending on the content of our database, we should get fifty (50) post titles.