In Laravel Blade, the $loop variable is a special helper variable that is automatically made available inside @foreach and @for loops. It gives you useful information about the current state of the loop.


Common $loop Properties

  • $loop->index The zero-based index of the current iteration (starts from 0).
  • $loop->iteration The one-based index of the current iteration (starts from 1).
  • $loop->remaining How many iterations are left (after this one).
  • $loop->count Total number of items in the loop.
  • $loop->first true if this is the first iteration.
  • $loop->last true if this is the last iteration.
  • $loop->even true if this is an even iteration (based on 1-based index).
  • $loop->odd true if this is an odd iteration (based on 1-based index).
  • $loop->depth The nesting level of the loop (1 for top-level loop, 2+ for nested).
  • $loop->parent Reference to the parent loop’s $loop variable (useful in nested loops).

Example Usage

<ul>
@foreach ($users as $user)
    <li>
        {{ $loop->iteration }}. {{ $user->name }}

        @if ($loop->first)
            - First user!
        @endif

        @if ($loop->last)
            - Last user!
        @endif
    </li>
@endforeach
</ul>

Nested Loops Example

@foreach ($categories as $category)
    <h2>{{ $category->name }}</h2>
    <ul>
        @foreach ($category->products as $product)
            <li>
                {{ $loop->parent->iteration }}.{{ $loop->iteration }} - {{ $product->name }}
            </li>
        @endforeach
    </ul>
@endforeach

Source: Orkhan Alishov's notes