Posts Learn Components Snippets Categories Tags About
/

Laravel Chunk Result

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

Created on Jul 23, 2021

41 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

Snippets by

PostSrc poster

PostSrc

Full stack developer mainly focusing on the front end side of the web. The main author of PostSrc and loves writing tutorial and guides online.

Load comments for Laravel Chunk Result

new

PostSrc Code Components

Collection of Tailwind CSS components for everyone to use. Browse all of the components that's right for your project.

View Components

Other Code Snippets

More