Posts Learn Components Snippets Categories Tags Tools About
/

Laravel Chunk Result

Learn how to chunk Laravel Collection to make iterating large data more efficient.

Created on Jul 23, 2021

204 views

In this snippet, you will learn how to chunk Laravel collection to better enhance the speed of your iteration and reduce the memory usage when processing over tens of thousand of records.

Laravel Fluent
To chunk collection using the Laravel Fluent interface, you can write your code like below. By chunking the collection into smaller numbers you will have better performance when iterating over a large number of data.
<?php

use Illuminate\Support\Facades\DB;

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

Laravel Eloquent
To chunk collection from Laravel Eloquent you can just call out the model that you want to query. By defining it like below the code is much more expressive and you can reduce the number of data loaded into the memory.
use App\Models\Post;

Post::chunk(200, function ($posts) {
    foreach ($posts as $post) {
        //
    }
});

Pro Tip: Using Cursor

If you like our tutorial, do make sure to support us by being our Patreon or buy us some coffee ☕️

Load comments for Laravel Chunk Result

)