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