Is there a way split the results of an eloquent search when using it in blade? I ask as I have a bootstrap carousel which is 2 slides split into 3 columns in each slide. I would like to have it so that each slide is filled out with the results of the following search:
$alsoBought = Game::where('category_id', $showGames['category_id'])->paginate(6);
As you can see, it brings back 6 results. Is there a way to split it so that there's 3 results on each slide? Here's my slide code:
<div id="carouselExampleSlidesOnly" class="carousel slide" data-ride="carousel">
<div class="carousel-inner">
<div class="carousel-item active">
<div class="row">
@foreach($alsoBought->take(3) as $bought)
<div class="col-4"><img class="w-100" src="{{ $bought['image'] }}" alt="First slide"></div>
@endforeach
</div>
</div>
<div class="carousel-item">
<div class="row">
@foreach($alsoBought as $bought)
<div class="col-4"><img class="w-100" src="{{ $bought['image'] }}" alt="First slide"></div>
@endforeach
</div>
</div>
</div>
</div>
You can use chunk()
on the collection instead of take()
and pass the amount of items you want in each chunk
@foreach($alsoBought->chunk(3) as $three)
<div class="carousel-item @if ($loop->first) active @endif">
<div class="row">
@foreach($three as $bought)
<div class="col-4"><img class="w-100" src="{{ $bought['image'] }}" alt="First slide"></div>
@endforeach
</div>
</div>
@endforeach
From the docs
The chunk
method breaks the collection into multiple, smaller collections of a given size:
$collection = collect([1, 2, 3, 4, 5, 6, 7]);
$chunks = $collection->chunk(4);
$chunks->toArray();
// [[1, 2, 3, 4], [5, 6, 7]]
Imagine a situation that you have 10 records to show in Blade but you need to show them in 2 sections, five records each. There's a pretty nice trick how to do that in @foreach loop use chunk
.
Try this.
<div id="carouselExampleSlidesOnly" class="carousel slide" data-ride="carousel">
<div class="carousel-inner">
@foreach($alsoBought->chunk(3) as $bought)
<div class="carousel-item @if($loop->first) {{ 'active' }} @endif">
<div class="row">
@foreach($bought as $item)
<div class="col-4"><img class="w-100" src="{{ $item['image'] }}" alt="First slide"></div>
@endforeach
</div>
</div>
@endforeach
</div>
</div>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.