Jason
Jason

Reputation: 109

Getting first element of loop in blade

I'm trying to get only first element which is presented in the loop. So if I have something like

@foreach($entries as $entry)
@if($element == 1)
     // do something
@else
     // do something else
@endif
@endforeach

Upvotes: 7

Views: 15086

Answers (1)

S.I.
S.I.

Reputation: 3375

You can use loop.first more information here

@foreach($array as $key => $value)
     @if($loop->first)
           // do something
     @else
           // do something else
     @endif
@endforeach

By default, blade doesn't have @break and @continue which are useful to have. So that's included.

Furthermore, the $loop variable is introduced inside loops, (almost) exactly like Twig.

loop.first True if first iteration

There is other way also like this but you'll have problems if there is not element starting with 0

....
if($key == 0)
....

Upvotes: 13

Related Questions