如何在 Laravel Blade 中拆分 foreach 循环

Mat*_*t B 1 php laravel eloquent

在刀片中使用雄辩搜索的结果时,有没有办法拆分它?我问,因为我有一个 bootstrap carousel,它是 2 张幻灯片,每张幻灯片分成 3 列。我想要它,以便每张幻灯片都填写以下搜索的结果:

 $alsoBought = Game::where('category_id', $showGames['category_id'])->paginate(6);
Run Code Online (Sandbox Code Playgroud)

如您所见,它带回了 6 个结果。有没有办法拆分它,以便每张幻灯片上有 3 个结果?这是我的幻灯片代码:

<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>
Run Code Online (Sandbox Code Playgroud)

Sal*_*301 7

您可以chunk() 在集合上使用而不是take()在每个块中传递您想要的项目数量

@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
Run Code Online (Sandbox Code Playgroud)

文档

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
Run Code Online (Sandbox Code Playgroud)