#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.
| Property | Type | Description |
|---|
$loop->index | int | Zero-based position (first item is 0) |
$loop->iteration | int | One-based position (first item is 1) |
$loop->count | int | Total number of items in the array |
$loop->remaining | int | Number of items left after the current one |
$loop->first | bool | true on the first iteration |
$loop->last | bool | true on the last iteration |
$loop->even | bool | true when index is even (0, 2, 4…) |
$loop->odd | bool | true when index is odd (1, 3, 5…) |
$loop->depth | int | Nesting depth — 1 for the outermost loop |
$loop->parent | object|null | The $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:
| Directive | Effect |
|---|
#break | Exit the current loop |
#break(N) | Exit N levels of nested loops |
#continue | Skip 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