chunks

Laravel Blade foreach “trick”: splitting results into chunks

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:

But there’s a better way – to use chunk() function of Collections.

You can read more about chunk() method here.

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

Want to generate Laravel adminpanel online?
You don't need any packages to do that!

2 thoughts on “Laravel Blade foreach “trick”: splitting results into chunks

Leave a Reply

Your email address will not be published. Required fields are marked *