Skip to main content
Tutorial Free

Laravel Blade foreach "trick": splitting results into chunks

October 18, 2017
1 min read

Imagine a situation that you have 10 records to show in Blade but you need to show them in 2 sections, five records each. There's a pretty nice trick how to do that in @foreach loop.

To rephrase - you have array of 10 records but you want to show them like this:

Section 1

  • Item 1
  • Item 2
  • Item 3
  • Item 4
  • Item 5

Section 2

  • Item 6
  • Item 7
  • Item 8
  • Item 9
  • Item 10

Straightforward way - you can use a $loop variable for this:

@foreach($items as $item)
    @if($loop->first or $loop->iteration % 5 == 0)
        <ul>
    @endif
    <li>
        Item {{ $loop->iteration }}
    </li>
    @if($loop->last == true or $loop->iteration % 5 == 0)
        </ul>
    @endif
@endforeach

But there's a better way - to use chunk() function of Collections.

@foreach($items->chunk(5) as $chunk)
    <ul>
        @foreach($chunk as $item)
            Item {{ $loop->iteration }}
        @endforeach
    </ul>
@endforeach

You can read more about chunk() method here.

Also, I've written this article a while ago: Process big DB table with chunk() method

Enjoyed This Tutorial?

Get access to all premium tutorials, video and text courses, and exclusive Laravel resources. Join our community of 10,000+ developers.

Comments & Discussion

No comments yet…

We'd Love Your Feedback

Tell us what you like or what we can improve

Feel free to share anything you like or dislike about this page or the platform in general.