DEV Community

Timothy Soladoye
Timothy Soladoye

Posted on

PHP Blade Loop Variable $loop variable

Below is a snippet from a project of mine. The first column of the table is for S/N. starting at 1.

Note the variable $loop

@foreach($payments as $payment)
       <tr>
          <td>{{$loop->index+1}}</td>
          <td>{{$payment->reference}}</td>
       </tr>
@endforeach
Enter fullscreen mode Exit fullscreen mode

It is called the Loop variable.
During the execution of a foreach loop, you will have access to a $loop variable within the loop itself.

You can check if the current iteration is the first using
$loop->first

@foreach($payments as $payment)
       @if($loop->first)
           This is the first iteration.
       @endif($loop->first)
@endforeach
Enter fullscreen mode Exit fullscreen mode

In a case of nested loop, you have access to the parent loop using
$loop->parent

@foreach ($users as $user)
    @foreach ($user->posts as $post)
        @if ($loop->parent->first)
            This is the first iteration of the parent loop.
        @endif
    @endforeach
@endforeach
Enter fullscreen mode Exit fullscreen mode

Other useful variables available on the $loop variables are

Property Description
$loop->index The index of the current loop iteration (starts at 0).
$loop->iteration The current loop iteration (starts at 1).
$loop->remaining The iterations remaining in the loop.
$loop->count The total number of items in the array being iterated.
$loop->first Whether this is the first iteration through the loop.
$loop->last Whether this is the last iteration through the loop.
$loop->even Whether this is an even iteration through the loop.
$loop->odd Whether this is an odd iteration through the loop.
$loop->depth The nesting level of the current loop.
$loop->parent When in a nested loop, the parent's loop variable.

Top comments (0)