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

October 26, 2018

If you have the following code in a Blade file:

<?php
@foreach(\User::all() as $user)
@endforeach

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

The $loop object has the following data:

<?php
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)
   ["depth"]=>int(1)
   ["parent"]=>NULL
}

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

<?php
@foreach(\App\User::all() as $user)
    @if($loop->first)
        Here are our users:
        <div>
    @endif
    {{$user->name}}
    @if($loop->last)
        </div>
        That was everyone!
    @endif
@endforeach

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