Home / Snippets / Laravel Chunk Result
Laravel Chunk Result cover

Laravel Chunk Result

317

2 years ago

0 comments

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
notion avatar

Ahabz

Week-end developer currently experimenting with web, mobile, and all things programming.

Topics:

Frontend

Resource

Average

Average

Support Us

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

Welcome to PostSrc V3

PostSrc Dark Logo

You have to login to favorite this