Laravel Blade Foreach Loop Example
Sep 17, 2022, Originally published at techvblogs.com ・2 min read
What is Blade Template in Laravel?
The blade is the template engine of Laravel. It's a very simple and powerful template engine of Laravel. In Blade, You can write HTML or PHP code into that file. There are so many blade directives in Laravel which you can use for multiple purposes. Blade template file uses .blade.php
file extension and it's stored in the resources/views
directory.
In this article, We will learn how to use foreach loop in the Blade template in laravel. Basically, When we need to display dynamic data from the array or database. Where data come through the array we need to use foreach loop inside the blade file.
The foreach loop works only on arrays and is used to loop through each key/value pair in an array. The foreach loop - Loops through a block of code for each element in an array.
Laravel Blade Foreach Loop Example
resources/views/users.blade.php
<!DOCTYPE html>
<html>
<head>
<title>Laravel Blade Foreach Loop Example - TechvBlogs</title>
</head>
<body>
<ul>
@foreach ($users as $user)
<li>Id: {{ $user['id'] }}, Name: {{ $user['name'] }}</li>
@endforeach
</ul>
</body>
</html>
app/Http/Controllers/UsersController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class UsersController extends Controller
{
/**
* Create a new controller instance.
*
* @return void
*/
public function index()
{
$users = [
[ 'id' => 1, 'name' => 'Alex'],
[ 'id' => 2, 'name' => 'Alan'],
[ 'id' => 3, 'name' => 'Tom'],
];
return view('users', compact('users'));
}
}
Using the loop variable inside foreach in Laravel
$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.
Source of the table from laravel
Here, We can check inside a loop whether it's the last iteration or not. You can see this in the below example.
<!DOCTYPE html>
<html>
<head>
<title>Laravel Blade Foreach Loop Example - TechvBlogs</title>
</head>
<body>
<ul>
@foreach ($users as $user)
<li>Id: {{ $user['id'] }}, Name: {{ $user['name'] }}</li>
@if ($loop->last)
<li>Last Data</li>
@endif
@endforeach
</ul>
</body>
</html>
Thank you for reading this article.