The Substitution Of Laravel Chunk To Process Big Data Example

Hello Artisan,

In this example, I am going to share with you a tutorial that can boost your Laravel application's performance. You know that, if you work with millions of record data then you need to chunk your Laravel collection and then you process them.

In this example, I will share with you the same type of situation and we will overcome that problem without using Laravel chunk. Do you know that? Yes, there is another helper method that can help us to process big data in Laravel perfectly without any doubt.

Look at the below example with Laravel chunk:

use Illuminate\Support\Facades\DB;

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


Look, we use chunk to chunk our big data. Now what we can do if we avoid chunks and do the same type of solution to handle big data. Yes, there is another helper called lazy() which can give us the same type of result to process big data. The important thing is that lazy method works similarly to chunk in the sense that it executes the query in chunks

This Laravel lazy() method returns a LazyCollection, which lets you interact with the results as a single stream. See the below example to understand:

use Illuminate\Support\Facades\DB;

DB::table('users')->orderBy('id')->lazy()->each(function ($user) {
    //process your big data


Recommended: Use toBase in Eloquent to Reduce Memory in Laravel


Hope this lazy() collection tutorial will help you to learn new things.


#laravel #laravel-8x #eloquent-tips