Laravel Blade Templates Control Structures


Blade provides convenient syntax for common PHP control structures.

Each of the control structures begins with @[structure] and ends with @[endstructure]. Notice that within the tags, we are just typing normal HTML and including variables with the Blade syntax.


'If' statements

@if ($i > 10)
    <p>{{ $i }} is large.</p>
@elseif ($i == 10)
    <p>{{ $i }} is ten.</p>
    <p>{{ $i }} is small.</p>

'Unless' statements

(Short syntax for 'if not'.)

@unless ($user->hasName())
    <p>A user has no name.</p>


'While' loop

@while (true)
    <p>I'm looping forever.</p>

'Foreach' loop

@foreach ($users as $id => $name)
    <p>User {{ $name }} has ID {{ $id }}.</p>

'Forelse' Loop

(Same as 'foreach' loop, but adds a special @empty directive, which is executed when the array expression iterated over is empty, as a way to show default content .)

@forelse($posts as $post)
    <p>{{ $post }} is the post content.</p>
    <p>There are no posts.</p>

Within loops, a special $loop variable will be available, containing information about the state of the loop:

$loop->indexThe index of the current loop iteration (starts at 0).
$loop->iterationThe current loop iteration (starts at 1).
$loop->remainingThe remaining loop iterations.
$loop->countThe total number of items in the array being iterated.
$loop->firstWhether this is the first iteration through the loop.
$loop->lastWhether this is the last iteration through the loop.
$loop->depthThe nesting level of the current loop.
$loop->parentWhen in a nested loop, the parent's loop variable.


@foreach ($users as $user)
  @foreach ($user->posts as $post)
        @if ($loop->parent->first)
            This is first iteration of the parent loop.

Since Laravel 5.2.22, we can also use the directives @continue and @break

@continueStop the current iteration and start the next one.
@breakStop the current loop.

Example :

@foreach ($users as $user)
    @continue ($user->id == 2)
        <p>{{ $user->id }} {{ $user->name }}</p>
    @break ($user->id == 4)

Then (assuming 5+ users are sorted by ID and no ID is missing) the page will render

1 Dave
3 John
4 William