Find last iteration of foreach loop in laravel blade Find last iteration of foreach loop in laravel blade php php

Find last iteration of foreach loop in laravel blade


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


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


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