Find the last iteration of the foreach loop in the cuff blade

In the wedge template, I use the last () method to find the last iteration of the foreach loop:

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

Everything is good? Perhaps there is a Laravel-style way to do the same?

+5
source share
5 answers

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 
+21
source

What you do is absolutely fine if you want to get an instance of the last item in the collection.

In addition, in Laravel 5.3 you can use the $loop variable, which allows you to get boolean for the last iteration $loop->last or get the current iteration index $loop->iteration , the total number of entries $loop->count and a few more loop variable

 @foreach ($posts as $post) {{ $post->title }} ({{ $loop->iteration }} of {{ $loop->count }}) @endforeach 
+4
source

if $colors is Collection , $colors->last() and end($colors) , both work

+3
source
 @foreach ($colors as $v) <option value={!! $v->id !!} {!!($v == end($colors)) ? 'selected="selected"' : '' !!} > {!! $v->name !!} </option> @endforeach 

or

 @foreach ($colors as $v) <option value={!! $v->id !!} {{($v == end($colors)) ? 'selected="selected"' : '' }} > {!! $v->name !!} </option> @endforeach 
+1
source

I don't know if this last method works, but if not, try the following:

 @foreach ($colors as $v) <option value={!! $v->id !!} @if($v == end($colors)) 'selected' @endif > {!! $v->name !!} </option> @endforeach 
0
source

Source: https://habr.com/ru/post/1244975/


All Articles