在Laravel Blade中查找foreach循环的最后一次迭代

问题描述:

在刀片模板中,我使用last()方法查找foreach循环的最后一次迭代:

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

可以吗?也许有Laravel风格的方法可以做到这一点?

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

对于Laravel 5.3+,您可以使用 $ loop 变量

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