Laravel blade foreach loop example; In this tutorial, you will learn how to use foreach loop in laravel blade file. Loop is very important for array values to show in the blade file.
Laravel blade provides an easy way to iterate a long list array or loop using @foreach and @for. @foreach and @for both used the same structure as PHP foreach and for. The below example of foreach loop statement in laravel 5, laravel 6, laravel 7, Laravel 8, or laravel 9 apps.
Syntax:
The syntax for foreach loop:
@foreach ($users as $user)
<p>This is user {{ $user->id }}</p>
@endforeach
Example:
Let’s understand Laravel blade foreach with example
<!DOCTYPE html>
<html>
<head>
<title>Laravel Blade Foreach Loop Example - codingdriver.com</title>
</head>
<body>
@foreach ($users as $key => $user)
This is index {{$key}} and user id is = {{ $user->id }}
@endforeach
</body>
</html>
Using loop variable inside foreach
$loop
the variable is used inside the foreach loop to access some useful information like first, last, count, index, etc. Below is the list of use 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
I hope its works for you.