In this laravel eloquent chunk method example tutorial, you will learn how to laravel chunk method with large records.
As well as you learn How to insert big data on the laravel by using chunk.
Laravel Eloquent Chunk() Method
Basically, Laravel eloquent chunk method break the large group of data set into smaller group of data set (chunks).
Suppose, if you work with any big laravel apps and work with large group of records from the database. At that time laravel chunk method will help you break a larger group of data set into a smaller groups of data set (chunks).
Let’s understand laravel chunk method through examples:
Example 1: Use laravel chunk with Eloquent Model
Controller:
$users
= User::all();
// Fetch some data
View:
@foreach($users->chunk(3) as $row)
<div class="grid__row">
@foreach($row as $user)
<div class="grid__item">
{{ $user->name}}
</div>
@endforeach
</div>
@endforeach
This method work with all types of laravel collections, see the following example:
$colors = collect(['orange', 'blue', 'green', 'red', 'yellow', 'purple']);
$chunks = $colors->chunk(3);
print_r($chunks);
/*
Output:
Array
(
[0] => Array
(
[0] => orange
[1] => blue
[2] => green
)
[1] => Array
(
[3] => red
[4] => yellow
[5] => purple
)
)
*/
Example 2: Send Email with Laravel chunk
Suppose you have 10000 emails id. And you want to send an email to everyone. But sometimes the problem comes that together you cannot send email on 10000 emails.
So for this, you can use Chunk method of Laravel. This will divide your large records of email ids into small groups of sets (chunks). And you can easily send mail to everyone.
For example like you have 10000 email ids. And You can send emails by chunk the email ids in 100 groups into smaller groups.
See the following example:
User::orderBy('id')->chunk(100, function ($users) {
foreach ($users as $user) {
// write your email send code here
}
});
Here, it will get all 10000 records from the DB table then chunk them by 100 and load in the memory.
Insert big data on the laravel
If may want to insert big data on laravel app, you can use laravel chunk as follow:
Laravel chunk will work on the collection, so change your items array to collection:
$items = collect($items);
Make chunk of your choice
$chunks = $items->chunk(100);
Then do a foreach and insert by 100 each time
foreach($chunks as $chunk){
DB::table('items')->insert($chunk->toArray());
}