How can I create only 4 cards on each line using bootstrap & laravel (@foreach)

Viewed 811
**@foreach($posts as $post)**

<div class="card">
    <img class="card-img-top" src="..." alt="Card image cap">
    <div class="card-body">
        <h5 class="card-title">**{{$post->title}}**</h5>
        <p class="card-text">**{{$post->description}}**</p>
        <p class="card-text">**{{$post->price}}**</p>
    </div>
</div>

**@endforeach**

I want to create 4 inline cards to display all post (4 cards on each line).

I tried to put the past code in

<div class="card-group">
**here**
</div>

but the result is many cards on the same line.

What's the best way to create a known number of cards (4) on each line using bootstrap and laravel @foreach?

1 Answers

Use the chunk() method and a nested loop:

@foreach($posts->chunk(4) as $chunk)
  <div class="card-group">
    @foreach($chunk as $post)
      <div class="card">...</div>
    @endforeach
  </div>
@endforeach

For reference: https://laravel.com/docs/8.x/collections#method-chunk.

This will split your $posts Collection into groups of 4 (or less), which you can then iterate, create a card-group for each chunk, and a card for each post within the chunk.

Related