phphtmllaravelforeach

Recognizing the last iteration of @foreach in Laravel Blade


I'm making a blog and I've separated each blog post with an <hr> tag. How to get rid of an <hr> in the last iteration. Here is my Code

@foreach($posts as $post)
  <div class="row">
    <div class="col-md-6">
      <h1>some title</h1>
      <p>some text</p>
    </div>
  </div>

  <hr>
@endforeach

Solution

  • You can use this simple logic, you can use count() method of collection and compare it to the keys in foreach:

    @php
      $posts_count = $posts->count();
    @endphp
    
    @foreach($posts as $key => $post)
        <div class="row">
        <div class="col-md-6">
        <h1>some title</h1>
        <p>some text</p>
        </div>
        </div>
    
        @if ($key + 1 != $posts_count)
            <hr>
        @endif
    @endforeach
    

    Hope this helps!