Limiting the results in Blade foreach loop

A cleaner way to do it could be this if it is a collection:

@foreach ($element['subs']->slice(0, 10) as $item)
 ...Code
@endforeach

another way for collections:

@foreach ($element['subs']->take(10) as $item)
 ...Code
@endforeach

or this if it is an array:

@foreach (array_slice($element['subs'], 0, 10) as $item)
 ...Code
@endforeach

Late, but to extend Pawel Bieszczad's answer in laravel 5.4 you can use the index property of the loop variable:

@foreach ($element['subs'] as $item)
    @if($loop->index < 10)
        // Your code
    @endif
@endforeach

You should limit the results in controller, but here's how you can accomplish this in a blade. Not pretty.

<?php $count = 0; ?>
@foreach ($element['subs'] as $item)
    <?php if($count == 10) break; ?>
    // Your code
    <?php $count++; ?>
@endforeach

Tags:

Laravel

Blade