You know that blade is a template engine and we can not write normal PHP code without using the @php
@endphp
blade directive. But all the PHP loops are available in the blade template engine and we can easily use them in the Laravel blade file.
In this tutorial, I will show you how we can use all the loops, like for loop
, while loop
, foreach loop
and forelse loop
in Laravel blade.
For Loop in Laravel Blade
@for ($i = 0; $i < 10; $i++)
The current value is {{ $i }}
@endfor
Foreach Loop in Laravel Blade
@foreach ($users as $user)
<p>This is user {{ $user->id }}</p>
@endforeach
Forelse Loop in Laravel Blade
@forelse ($users as $user)
<li>{{ $user->name }}</li>
@empty
<p>No users</p>
@endforelse
While Loop in Laravel Blade
@while (true)
<p>I'm looping forever.</p>
@endwhile
Remember: While iterating through a
foreach
loop, you may use the loop variable;
Example code of loop variable inside foreach 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
There are so many loop variables in Laravel. See the below image:
Read also: How To Use Switch Statement In Laravel Blade
Hope it can help you.