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?

5 Answers 11

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

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

@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

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
upvote
  flag
+1 Also, I think it's worth mentioning the $loop->last bit itself, which solves the main issue of this question. – kefir500
up vote 18 down vote accepted

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
1 upvote
  flag
You might wanna correct the if-condition It should have parentheses instead of double curly-braces :) – andersevenrud
3 upvote
  flag
Only works from Laravel version 5.3 – Hos Mercury

Not the answer you're looking for? Browse other questions tagged or ask your own question.