Find last iteration of foreach loop in laravel blade

PhpLaravelLaravel 5BladeLaravel Blade

Php Problem Overview


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?

Php Solutions


Solution 1 - Php

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

Solution 2 - Php

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

Additionally, in Laravel 5.3 you can use $loop variable, which allows you to get boolean for last iteration $loop->last or to obtain current iteration index $loop->iteration, total number of records $loop->count and a few more The Loop Variable

@foreach ($posts as $post)

	{{ $post->title }} ({{ $loop->iteration }} of {{ $loop->count }})	

@endforeach

Solution 3 - Php

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

Solution 4 - Php

@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

Solution 5 - Php

Don't know if that last method is working but if not, try this:

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser947668View Question on Stackoverflow
Solution 1 - PhpTom KurView Answer on Stackoverflow
Solution 2 - PhpSebastian SulinskiView Answer on Stackoverflow
Solution 3 - PhpcresjieView Answer on Stackoverflow
Solution 4 - PhpMohammad GitipasandView Answer on Stackoverflow
Solution 5 - PhpbimView Answer on Stackoverflow