Find last iteration of foreach loop in laravel blade

后端 未结 5 1603
隐瞒了意图╮
隐瞒了意图╮ 2021-02-06 22:03

In blade template i use last() method to find last iteration of foreach loop:

@foreach ($colors as $k => $v)
   
相关标签:
5条回答
  • 2021-02-06 22:41
    @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
    
    0 讨论(0)
  • 2021-02-06 22:42

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

    0 讨论(0)
  • 2021-02-06 22:44

    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
    
    0 讨论(0)
  • 2021-02-06 22:45

    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
    
    0 讨论(0)
  • 2021-02-06 23:01

    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
    
    0 讨论(0)
提交回复
热议问题