繁体   English   中英

如何在 laravel 刀片中拆分 foreach 循环

[英]How to split a foreach loop in laravel blade

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

 $alsoBought = Game::where('category_id', $showGames['category_id'])->paginate(6);

如您所见,它带回了 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>

您可以在集合上使用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

文档

chunk方法将集合分解为多个给定大小的较小 collections:

$collection = collect([1, 2, 3, 4, 5, 6, 7]);

$chunks = $collection->chunk(4);

$chunks->toArray();

// [[1, 2, 3, 4], [5, 6, 7]]

想象一下,您有 10 条记录要在 Blade 中显示,但您需要在 2 部分中显示它们,每部分 5 条记录。 在 @foreach 循环中使用chunk有一个非常好的技巧。

尝试这个。

<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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM