How to find out what is the first or last item of the Loop in Laravel?

Asked

Viewed 412 times

3

I got the following foreach in Laravel.

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

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

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

For example, the Twig:

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

Is there any way to do this in Laravel?

2 answers

3


As far as 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

With regard to loops the new Laravel 5.3 also brought us, in addition to these on top, some methods (of the new stdClass $loop) that may be useful, ex:

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

$loop->iteration is information about where back we are in the loop (account from 1), while $loop->count is the total number of laps (in this example is the total count of $users)

Reference and more examples here

  • +1, you are on top of the news. I was already thinking of answering :p

  • @Wallacemaxters was just playing with 5.3 :P

  • You may have other information that would be interesting to add to the question, such as that one. There are more things I imagined :D

  • Miguel, I’m going to do a search on Laravel 5.3. It was very good the answer. I’ll check which object he uses in the variable $loop, I’m a little suspicious that it’s some class that implements Recursiveiterator.

  • Yap maybe it is, it’s true @Wallacemaxters

2

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

You can do what you need by the foreach index:

@foreach($values as $i=>$value)
  <li>
      @if($i==0)
          Primeiro
      @elseif($i==count($value)-1)
          Ultimo
      @else
      {{ $value }}
      @endif
  </li>
@endforeach
  • It also works. But, as Miguel answered, there’s a new feature in Laravel 5.3.

  • 1

    Is that he answered while still writing rsrsrs

Browser other questions tagged

You are not signed in. Login or sign up in order to post.