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
Leave a reply