php - Laravel 8 display 4th, 5th and 6th elements of a collection
Solution:
If you're in a blade, using bootstraps containers, rows and cards:
<div class="container">
@foreach($players as $player)
@if($loop->first)
<div class="row"> //first iteration, start a row
@endif
//each element is a cart
<div class="card">
<div class="card-header">
</div>
<div class="card-body" style="padding: 3px">
</div>
</div>
@if(($loop->iteration % 3 == 1)&&(!$loop->last))
//every 3rd iteration, and not the last, end the current row and start a new one
</div>
<div class="row">
@endif
@if($loop->last)
</div>//if it's the last iteration, end the row
@endif
@endforeach
</div>
This is just basic array looping, don't have to get complicated or fancy. More on the Laravel $loop variable here:
https://laravel.com/docs/8.x/blade#the-loop-variable
Answer
Solution:
I don't get well your use case, but you could use the method of the Collection class:
$players = Player::where('...')->get();
$chunks = $players->chunk(3);
foreach($chunks as $chunk) {
foreach($chunk as $player) {
// ...
}
}
Or, in case you are in Blade:
@foreach ($players->chunk(3) as $chunk)
<div class="row">
@foreach ($chunk as $player)
<div class="col-xs-4">{{ $player->name }}</div>
@endforeach
</div>
@endforeach
Answer
Solution:
You can also use the skip()
and take()
helper function to achieve that. For example.
Model::skip(3)->take(2)->get();
will give you the 4th and 5th rows.
Source