Skip to main content

#foreach / #endforeach

Use #foreach to iterate over any array or iterable. The syntax mirrors PHP’s foreach expression.
#foreach($posts as $post)
    <article class="{{ $loop->even ? 'even' : 'odd' }}">
        <h2>{{ $loop->iteration }}. {{ $post->title }}</h2>

        #if($loop->first)
            <span class="badge">Latest</span>
        #endif
    </article>
#endforeach
You can also iterate with a key:
#foreach($config as $key => $value)
    <dt>{{ $key }}</dt>
    <dd>{{ $value }}</dd>
#endforeach

The $loop variable

Inside every #foreach block, Lex automatically injects a $loop object with metadata about the current iteration.
PropertyTypeDescription
$loop->indexintZero-based position (first item is 0)
$loop->iterationintOne-based position (first item is 1)
$loop->countintTotal number of items in the array
$loop->remainingintNumber of items left after the current one
$loop->firstbooltrue on the first iteration
$loop->lastbooltrue on the last iteration
$loop->evenbooltrue when index is even (0, 2, 4…)
$loop->oddbooltrue when index is odd (1, 3, 5…)
$loop->depthintNesting depth — 1 for the outermost loop
$loop->parentobject|nullThe $loop object of the enclosing loop, or null if none

Nested loops

In nested #foreach blocks, $loop always refers to the innermost loop. Access the outer loop’s metadata through $loop->parent.
#foreach($categories as $category)
    <h2>{{ $category->name }}</h2>

    #foreach($category->products as $product)
        <p>
            Category {{ $loop->parent->iteration }} /
            Product {{ $loop->iteration }}:
            {{ $product->name }}
        </p>
    #endforeach
#endforeach
$loop->parent->parent works for three or more levels of nesting.

#for / #endfor

Use #for when you need a counter-controlled loop. The expression is a standard PHP for header.
#for($i = 1; $i <= 5; $i++)
    <p>Step {{ $i }}</p>
#endfor
The $loop variable is not injected inside #for or #while blocks — it is only available in #foreach.

#while / #endwhile

Use #while to loop as long as a condition holds.
#while($queue->isNotEmpty())
    {{ $queue->pop() }}
#endwhile

Loop control

Use #break and #continue inside any loop directive to alter the iteration flow.
#foreach($items as $item)
    #if($item->isHidden())
        #continue
    #endif

    #if($item->isLast())
        #break
    #endif

    {{ $item->name }}
#endforeach
Both directives accept a numeric argument to break or continue multiple levels at once:
DirectiveEffect
#breakExit the current loop
#break(N)Exit N levels of nested loops
#continueSkip to the next iteration of the current loop
#continue(N)Skip to the next iteration N levels up
#foreach($groups as $group)
    #foreach($group->items as $item)
        #if($item->isBlocked())
            #break(2)
        #endif

        {{ $item->name }}
    #endforeach
#endforeach

Build docs developers (and LLMs) love