Blade Templates and the $loop variable

Check this out, y’all.

Have you ever found yourself setting a counter variable on a foreach loop and thinking “there has to be a better way!”


Well check out the $loop variable in Blade:

The loop variable is available inside @foreach loops and offers the following properties (blatantly stolen from the above-linked documentation):

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 iteration 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->depth The nesting level of the current loop.
$loop->parent When in a nested loop, the parent’s loop variable.

So you can do things like this:

@foreach ($users as $user)
    @if ($loop->first)
        This is the first iteration.

    @if ($loop->last)
        This is the last iteration.

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

How cool is that??


Nice I didnt realize this only worked for foreach loops only. Is there any way to get them to work with while loops?

1 Like

I wanted this too, so I wrote this directive for Wordpress loops.

Did you figure it out for while loops? :slight_smile:

1 Like