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:

@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

Like our articles?
Check out our Laravel online courses!

7 COMMENTS

  1. What if we have 10.000 entries and we want to display only 10?
    @foreach ($cards->take(10) as $card) would solve the problem but
    how we combine this with the chunk method?
    @foreach($items->take(10)->chunk(5) as $chunk) would that work?

  2. Please someone help me. I am not great at PHP and need a very simple help.

    I copied and pasted a code from my page, to another section of the same page. But I want them to display different data. Right now, each time the page loads, the same data is dsiplayed on these two sections. Kindly help me add the magic code so that they do NOT show the same data. This is the code below:

    @foreach($sub_categories as $sub_categorys)
    picture}});”>
    {{$sub_categorys->name}}
    {{tr(‘book_now’)}}

    @endforeach

LEAVE A REPLY

Please enter your comment!
Please enter your name here