Laravel Blade Templates Control Structures


Example

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.

Conditionals

'If' statements

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

'Unless' statements

(Short syntax for 'if not'.)

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

Loops

'While' loop

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

'Foreach' loop

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

'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>
@empty
    <p>There are no posts.</p>
@endforelse

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

PropertyDescription
$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.

Example:

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

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

PropertyDescription
@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)
@endforeach

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

1 Dave
3 John
4 William