Laravel Blade Templates: Control Structures
If Statements
Switch Statements
Loops
@for ($i = 0; $i < 10; $i++)
The current value is {{ $i }}
@endfor
@foreach ($users as $user)
<p>This is user {{ $user->id }}</p>
@endforeach
@forelse ($users as $user)
<li>{{ $user->name }}</li>
@empty
<p>No users</p>
@endforelse
@while (true)
<p>I'm looping forever.</p>
@endwhile
The Loop Variable
Provides access to some useful bits of information such as the current loop index and whether this is the first or last iteration through the loop.
@foreach ($users as $user)
@if ($loop->first)
This is the first iteration.
@endif
@if ($loop->last)
This is the last iteration.
@endif
<p>This is user {{ $user->id }}</p>
@endforeach
@foreach ($users as $user)
@foreach ($user->posts as $post)
@if ($loop->parent->first)
This is first iteration of the parent loop.
@endif
@endforeach
@endforeach
Available inside of your loop.
- $loop->index.
- $loop->iteration.
- $loop->remaining.
- $loop->count.
- $loop->first.
- $loop->last.
- $loop->depth.
- $loop->parent.