What is the loop variable in a @foreach loop in Blade?

October 26, 2018

If you have the following code in a Blade file:

@foreach(\User::all() as $user)

You have access to $user (obviously) but also the $loop object.

The $loop object has the following data:

object(stdClass)#290 (8) {
   ["iteration"]=> int(1) // starts at 1 (on first loop)
   ["index"]=> int(0) // starts at 0 (on first loop)
   ["remaining"]=> int(4)
   ["count"]=> int(5)
   ["first"]=> bool(true)
   ["last"]=> bool(false)

So if you wanted to do something different for the first or last rows then you could easily do this:

@foreach(\App\User::all() as $user)
        Here are our users:
        That was everyone!

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

see more