Baz Baz - 1 month ago 13
CSS Question

How to insert a div for every nth object in laravel

I have a foreach loop where I need to insert a div every nth object.

@if(count($articles))

@foreach($articles as $article)

@if(this is the nth object)
<div class="row margin-b-2">
@endif
<div class="col-sm-4">
<a style="background-color: {{ $article->category->color }}" href="{{ route('category', ['category_slug' => $article->category->slug]) }}">{{ $article->category->title }}</a>
</div>

@if(this is the nth object)
</div>
@endif
@endforeach
@endif


this is the bare bones of what I am trying to do.

Answer

I would use the modulus division operator. If for example you wanted it after every 9 articles:

<?php $counter = 1; ?>

@if(count($articles))

    @foreach($articles as $article)

        @if($counter % 9 == 0)
             <div class="row margin-b-2">
        @endif
        <div class="col-sm-4">
            <a style="background-color: {{ $article->category->color }}" href="{{ route('category', ['category_slug' => $article->category->slug])  }}">{{ $article->category->title }}</a>
        </div>

        @if($counter % 9 == 0)
           </div>
        @endif
   <?php $counter++; ?>
   @endforeach
 @endif

How this works: Modulus division returns the remainder. The remainder is always equal to 0 when you are at an even multiple.