Pinch Pinch - 27 days ago 7
HTML Question

How do I remove the last <hr> tag in a foreach loop in Laravel?

I'm making a blog and I've seperated each blog post with a

<hr>
tag. But at the bottom it also loops, because that's how my foreach loops is built.

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

<hr>
@endforeach


That will just output a horizontal line at every bottom of every div. Any help?

Answer

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!