kendrick's avatar

Horizontal row, odd logic

Yesterday, I learned how to implement a "space-filler" logic within a foreach loop (Thank you, @ftiersch), which checks if the number of the $collection is odd. If it is the case, it implements a "space-filler" to the current pagination, as I paginate(2). (Vertical loop)

// if odd
$users->count() % 2 != 0

This logic is super for a vertical foreach loop. If we imagine a horizontal loop, where we implement a row with three elements per row col-md-4, and max. our collection to lets say six elements (limit(6)->get() or paginate(6)), how could we fill the spaces per row, with the same logic in mind as within the vertical loop.

Currently a space filler logic looks like this:

1.) I limit the $collection within my Controller to e.g. 6.

And within my view, I implement this logic, and for every case either show one space filler or two (simple partials):

@if($users->count() == 1) 

<div class="row">
@foreach($users as $user)
<div class="col-md-4"> 
<p>{{$user->name}}</p> 
</div> 
@endforeach
<div class="col-md-4"><p>space-filler</p></div>
<div class="col-md-4"><p>space-filler</p></div>
</div>

@elseif($users->count() == 2) 
    
<div class="row">
@foreach($users as $user)
<div class="col-md-4"> 
<p>{{$user->name}}</p> 
</div> 
@endforeach
<div class="col-md-4"><p>space-filler</p></div>
</div>

@elseif($users->count() == 3) 

<div class="row">

@foreach($users as $user)
<div class="col-md-4"> 
<p>{{$user->name}}</p> 
</div> 
@endforeach
</div>

@elseif($users->count() == 4) 
... same as 1
@elseif($users->count() == 5) 
... same as 2
@elseif($users->count() == 6)
... same as 3
@endif 

Is there a more dynamic or efficient solution for that logic, a less redundant one? E.g.:

If I only count 1 User, I get 5 "space fillers"? (Horizontal loop)

0 likes
2 replies
ftiersch's avatar
ftiersch
Best Answer
Level 28

Thanks for the shout out ;-)

@foreach ($users as $user)
    // display one "user" here
@endforeach

@for($i = 3 - $users->count(); $i > 0; $i--)
    // display one "space filler" here
@endfor

That should do it :) Just dynamically start the for() loop where you need it to start. If you want a different number than "3 per row" you can just change the 3 to 5 for example.

1 like
kendrick's avatar

Super. It works like magic, again. Thank you.

Please or to participate in this conversation.