Laravel blade provides easy way to iterate a long list array or loop using @foreach
and @for
. @foreach
and @for
both used same structure as php foreach and for. In this article i will show you to use @foreach and @for loop with example and also the $loop
variable. Loop variable is always available inside the loop and we can access it using $loop object.
Here is the syntax for for
loop
@for ($count = 0; $count < 10; $count++)
The Counter value is {{ $i }}
@endfor
and syntax for foreach
loop
@foreach ($posts as $post)
<p>Title : {{ $post->title }}</p>
@endforeach
as we can see syntax is equivalent to php for loop, forelse
is also can be used if array is empty then we can show else block as below
@forelse ($posts as $post)
<li>{{ $post->title }}</li>
@empty
<p>No posts</p>
@endforelse
Using loop variable inside foreach
$loop
variable is used inside the foreach loop to access the some useful information like first, last, count, index etc. Below is the list of use of variables.
$loop->index | The index of the current loop iteration (starts at 0). |
$loop->iteration | The current loop iteration (starts at 1). |
$loop->remaining | The iterations remaining in the loop. |
$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->even | Whether this is an even iteration through the loop. |
$loop->odd | Whether this is an odd 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 of $loop variable
@foreach ($posts as $post)
@if ($loop->first)
This is the first iteration.
@endif
@if ($loop->last)
This is the last iteration.
@endif
<p>loop index {{ $loop->index}} </p>
@endforeach
Let’s understand Laravel blade foreach, for and loop variable with example
Step 1: Create a fresh laravel project
composer create-project --prefer-dist laravel/laravel blog
Step 2: Add routes in routes/web.php
Create routes to call our controller and blade file in it.
routes/web.php
<?php
use Illuminate\Support\Facades\Route;
Route::get('/example',function(){
$posts=[["title"=>"test","id"=>"1"],["title"=>"test2","id"=>"2"]];
return view("example-view",["posts"=>$posts]);
});
Step 3: Create View File
Now, create a example-view.blade.php
in resource/views
folder.
@foreach ($posts as $post)
@if ($loop->first)
This is the first iteration.
@endif
@if ($loop->last)
This is the last iteration.
@endif
<p>loop index {{ $loop->index}} </p>
<p>Title : {{ $post['title']}} </p>
@endforeach