# Blade Templates and the $loop variable

**URL:** https://discourse.roots.io/t/blade-templates-and-the-loop-variable/11246
**Category:** sage
**Tags:** sage9, blade
**Created:** 2018-01-04T19:49:02Z
**Posts:** 4

## Post 1 by @MWDelaney — 2018-01-04T19:49:03Z

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!”

![EDaoQ](https://discourse.roots.io/uploads/default/original/2X/3/31ba92c56ebe084abe99261b2c125f306d46e173.gif)

Well check out the `$loop` variable in Blade:

[https://laravel.com/docs/5.5/blade#the-loop-variable](https://laravel.com/docs/5.5/blade#the-loop-variable)

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.
    @endif

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

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

How cool is that??

---

## Post 2 by @pi_mont — 2018-01-05T18:37:26Z

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

---

## Post 3 by @Xilonz — 2018-02-27T10:55:12Z

I wanted this too, so I wrote [this](https://gist.github.com/Xilonz/c02e93ea08c25ab088e1fa54fcee69d9) directive for Wordpress loops.

---

## Post 4 by @trainoasis — 2019-03-05T00:52:44Z

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