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 ($i > 10)
<p>{{ $i }} is large.</p>
@elseif ($i == 10)
<p>{{ $i }} is ten.</p>
@else
<p>{{ $i }} is small.</p>
@endif
(Short syntax for 'if not'.)
@unless ($user->hasName())
<p>A user has no name.</p>
@endunless
@while (true)
<p>I'm looping forever.</p>
@endwhile
@foreach ($users as $id => $name)
<p>User {{ $name }} has ID {{ $id }}.</p>
@endforeach
(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:
Property | Description |
---|---|
$loop->index | The index of the current loop iteration (starts at 0). |
$loop->iteration | The current loop iteration (starts at 1). |
$loop->remaining | The remaining loop iterations. |
$loop->count | The total number of items in the array being iterated. |
$loop->first | Whether this is the first iteration through the loop. |
$loop->last | Whether this is the last iteration through the loop. |
$loop->depth | The nesting level of the current loop. |
$loop->parent | When 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
Property | Description |
---|---|
@continue | Stop the current iteration and start the next one. |
@break | Stop 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