Laravel chunk eloquent example; Through this tutorial, i am going to show you how to chunk() eloquent method in laravel apps.
Laravel eloquent chunk method break the large group of data set into smaller group of data set (chunks).
Laravel Chunk Eloquent Example
See the following examples of laravel chunk eloquent method; is as follows:
- Example 1: Laravel chunk with Eloquent Model
- Example 2: Send Email with Laravel chunk
- Example 3: Insert large data in db using laravel chunk
Example 1: Laravel chunk with Eloquent Model
If you want to fetch all data from database and want to display only some data. So, you can use chunk method; as follows:
$users = User::all(); // Fetch some data
Display data using laravel chunk; is as follows:
@foreach($users->chunk(3) as $row) <div class="grid__row"> @foreach($row as $user) <div class="grid__item"> {{ $user->name}} </div> @endforeach </div> @endforeach
Example 2: Send Email with Laravel chunk
If you have thousand of data for sending email, so you can use laravel chunk method to split data into smaller part for sending email in laravel apps; is as follows:
User::orderBy('id')->chunk(100, function ($users) { foreach ($users as $user) { // write your email send code here } });
Example 3: Insert large data in db using laravel chunk
If you have thousand of data for insert into database, so you can use laravel chunk method to split data into smaller part for insert data into database in laravel apps; is as follows:
$items = collect($items); $chunks = $items->chunk(100); foreach($chunks as $chunk){ DB::table('items')->insert($chunk->toArray()); }
Be First to Comment