How do I find out the first or last Loop item in Laravel?

3

I have the following foreach in Laravel.

@foreach($values as $value)
  <li>{{ $value }}</li>
@endforeach

I would like to add some special information when it comes to the first item in the loop.

In some other template engines, there is usually a specific method to know which is the first or last item in the loop.

For example, Twig:

{% for (value in values) %}
      <li>{% if loop.first %}Primeiro - {% endif %}{{ value }}</li>
{% endfor %}

Is there any way to do this in Laravel?

    
asked by anonymous 02.09.2016 / 16:57

2 answers

3

I know this only exists in the new Laravel 5.3:

@foreach ($users as $user)
    @if ($loop->first) // primeiro item do loop
        This is the first iteration.
    @endif

    @if ($loop->last) // ultimo item do loop
        This is the last iteration.
    @endif

    <p>This is user {{ $user->id }}</p>
@endforeach

Example taken from DOCS

As far as loops are concerned, the new Laravel 5.3 also brought us, in addition to the above, a few methods (new stdClass $loop ) that may be useful, eg:

@foreach ($users as $user)
    Já demos {{$loop->iteration}} voltas de um total de {{$loop->count}} voltas
@endforeach

$loop->iteration is information about which loop we are in (count from 1), while $loop->count is the total number of turns (in this example it is the total count of $users )

Reference and more examples here

    
02.09.2016 / 17:01
2

The Laravel blade is nothing more than a "cute" way of writing PHP in the html without having to do a lot of <?php echo $nome ?>

You can do what you need by indexing foreach:

@foreach($values as $i=>$value)
  <li>
      @if($i==0)
          Primeiro
      @elseif($i==count($value)-1)
          Ultimo
      @else
      {{ $value }}
      @endif
  </li>
@endforeach
    
02.09.2016 / 17:04