Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Sometimes, when filtering through a collection and displaying them on the page, you need to wrap every X items within a wrapper. Common examples are when using Bootstrap... Is this the recommended way to do that? Fairly clean as it is, I guess...
@foreach(array_chunk($posts, 3) as $postSet)
<div class="row"> <!-- this div will surround every three posts -->
@foreach($postSet as $post)
<h3>{{ $post['title'] }}</h3>
@endforeach
</div>
@endforeach
@JeffreyWay

This comment has been minimized.

Copy link
Owner Author

JeffreyWay commented Aug 16, 2013

I guess this is fine as is...was just curious if there was an alternative.

@zackkitzmiller

This comment has been minimized.

Copy link

zackkitzmiller commented Aug 16, 2013

There's a solution involving an additional partial, but I'm not sure if it's 'cleaner.'

@dhrrgn

This comment has been minimized.

Copy link

dhrrgn commented Aug 16, 2013

An alternative...a little harder to understand than yours, but just proposing it as an alternative

Edit: Downside is you would have extra h3 tags sitting there too (although you could fix that).

@for($i = 0, $count = count($posts); $i < $count; $i += 3)
   <div class="row"> <!-- this div will surround every three posts -->
        <h3>{{ array_get($posts, $i.'.title') }}</h3>
        <h3>{{ array_get($posts, ($i + 1).'.title') }}</h3>
        <h3>{{ array_get($posts, ($i + 2).'.title') }}</h3>
    </div>
@endforeach
@JeffreyWay

This comment has been minimized.

Copy link
Owner Author

JeffreyWay commented Aug 16, 2013

Or you could use the modulus trick. Mostly was wondering if there was any secret Eloquent method for handling this. I guess array_chunk is the easiest way to go about it.

@ammonkc

This comment has been minimized.

Copy link

ammonkc commented Aug 16, 2013

I was actually looking for this exact solution yesterday. This is much cleaner than what I came up with. Thanks.

@taylorotwell

This comment has been minimized.

Copy link

taylorotwell commented Aug 16, 2013

Hmm.. I can't think of anything much cleaner. Like Zack said maybe a partial thing. I dunno.

@tyler43636

This comment has been minimized.

Copy link

tyler43636 commented Feb 19, 2014

Whenever I try this, array_chunk complains about getting an object instead of an array. I'm passing an Eloquent model. Any tips?

@vishnupadmanabhan

This comment has been minimized.

Copy link

vishnupadmanabhan commented Mar 21, 2014

Try:

@foreach(array_chunk($posts->all(), 3) as $postSet)

instead of:

@foreach(array_chunk($posts, 3) as $postSet)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.