How to chunk query results in Laravel

Introduction

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.

What is the 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.

Syntax

DB::table('users')->orderBy('id')->chunk(100, function ($users) {
    foreach ($users as $user) {
        //
    }
}); 

Parameters

The chunk() method accepts two parameters or arguments:

  1. Chunk value: The number of records you want to fetch at a time.

  2. The Callback function.

Example

use Illuminate\Support\Facades\DB;

DB::table('posts')->orderBy('id')->chunk(50, function ($posts) {
    foreach ($posts as $post) {
        echo $post->title;
    }
});

Explanation

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.

Output

Depending on the content of our database, we should get fifty (50) post titles.

Free Resources