How to update chunk records in Laravel

Overview

While working with large amounts of data, it is a good practice to break or process the data in chunks. In this shot, we will learn how to use the chunkById() method in Laravel to carry updates on chunk data.

What is the chunkById() method?

The chunkById() method is used to paginate query results using the record primary key. This method enables us to accurately carry out operations on the record.

Syntax

DB::table('tablename')->chunkById(50,function(){})

Parameters

Just like the chunk() method, the chunkById() method receives two parameters:

  1. The chunk value, which is the amount of data to be chunked or processed at once.

  2. The callback function.

Example

use Illuminate\Support\Facades\DB;
public function updateChunk(){
DB::table('users')->where('active', false)
    ->chunkById(100, function ($users) {
        foreach ($users as $user) {
            DB::table('users')
                ->where('id', $user->id)
                ->update(['active' => true]);
        }
    });
}

Code explanation

From the code example given above, we can see how chunk data is updated. First, we import the DB class into our controller. Then, we create a updateChunk() function to make all the inactive users active. We first use the where() method to locate the inactive users. After we locate the inactive users, we use the chunkById() method to fetch 100 records all at once from the database with the help of their IDs. We pass the value 100 as a parameter and transfer it to the callback function, which then uses a foreach() method to update each of these results.