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.

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Retry later