Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find last iteration of foreach loop in laravel blade

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?

like image 202
user947668 Avatar asked Mar 13 '16 21:03

user947668


People also ask

How do I find my last foreach iteration?

Method 1: It is the naive method inside foreach loop to find iteration. Use a counter variable and check when the counter value is zero then it is the first iteration and when the counter value is length-1 then it is the last iteration.

What is foreach loop in laravel?

Laravel blade has a foreach directive that we can use the same way as we use the foreach loop in PHP. @foreach directive is more powerful than a normal foreach loop because of the $loop variable that is available inside every $foreach loop.


2 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 
like image 110
Tom Kur Avatar answered Sep 23 '22 16:09

Tom Kur


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 
like image 38
Sebastian Sulinski Avatar answered Sep 19 '22 16:09

Sebastian Sulinski