Find last iteration of foreach loop in laravel blade

user947668 picture user947668 · Mar 13, 2016 · Viewed 49.5k times · Source

In blade template i use last() method to find last iteration of foreach loop:

@foreach ($colors as $k => $v)
   <option value={!! $v->id !!} {{ $colors->last()->id==$v->id ? 'selected':'' }} > {!! $v->name !!} </option>
@endforeach

Is it ok? Perhaps there is a Laravel-style way to do the same?

Answer

Tom Kur picture Tom Kur · Dec 14, 2016

As for Laravel 5.3+, you can use the $loop variable

$loop->last

@foreach ($colors as $k => $v)
     @if($loop->last)
         // at last loop, code here
     @endif
@endforeach