Laravel Blade

Master Blade Foreach Iteration with the $loop Variable

Punyapal Shah 2 min read
edit this tip
Leverage Laravel's automatic $loop variable inside @foreach blocks to access iteration index, first/last status, even/odd flags, and parent loop context.

Inside every Blade @foreach loop, Laravel automatically injects a $loop object providing rich metadata about the current iteration without maintaining manual counter variables.

Key $loop Properties

@foreach ($users as $user)
    <div class="{{ $loop->first ? 'bg-primary' : '' }} {{ $loop->even ? 'row-alt' : '' }}">
        <span>#{{ $loop->iteration }}</span>
        <h3>{{ $user->name }}</h3>

        @if ($loop->last)
            <p>Total records: {{ $loop->count }}</p>
        @endif
    </div>
@endforeach

Full $loop Property Reference

PropertyDescription
$loop->indexThe index of the current iteration (0-indexed).
$loop->iterationThe current iteration count (1-indexed).
$loop->remainingThe number of iterations remaining.
$loop->countThe total number of items in the array being iterated.
$loop->firstWhether this is the first iteration.
$loop->lastWhether this is the last iteration.
$loop->evenWhether this is an even iteration.
$loop->oddWhether this is an odd iteration.
$loop->depthThe nesting level of the current loop.
$loop->parentThe $loop variable of the parent loop when nested.

Accessing Parent Loops in Nested Iterations

@foreach ($categories as $category)
    <h2>{{ $category->name }}</h2>

    @foreach ($category->posts as $post)
        {{-- Access parent category loop metadata --}}
        <p>Category #{{ $loop->parent->iteration }} - Post #{{ $loop->iteration }}: {{ $post->title }}</p>
    @endforeach
@endforeach

Summary

  • Automatically available in all Blade @foreach loops with zero setup.
  • $loop->iteration provides 1-indexed numbering for UI tables.
  • $loop->parent provides full access to enclosing loops in nested hierarchies.
Tags: Laravel Blade HTML Templates
Share on X

// Found an issue or want to contribute a tip? github.com/MrPunyapal/tips