Reputation: 55
I'm trying to show items in rows in Laravel 8. The first row is easy enough. The first 3 items of the collection, using a counter and a foreach loop.
$i = 0;
foreach($players as $player){
$i +=1;
what to do each loop
if($i == 3) break;
}
But if I want the 4th, 5th and 6th items on the second row, how would I do that? I tried array_slice which didn't work because a collection is not an array. Secondly, apparently, I cannot tell a forEach loop where to start.
Upvotes: 0
Views: 864
Reputation: 379
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
Upvotes: 2
Reputation: 1229
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.
Upvotes: 0
Reputation: 14271
I don't get well your use case, but you could use the chunck()
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
Upvotes: 0