Laravel Blade foreach loop example

This article is focused on laravel blade foreach loop example. You will learn laravel foreach loop in blade. We will help you to give example of laravel foreach loop example. Consider below step for foreach laravel blade.

What is blade template in laravel?

The blade is the template engine of laravel. It’s a very simple template engine of laravel. In Blade file, you can write code that file. Blade template file uses .blade.php file extension and it’s stored in the resources/views directory.

The foreach loop works only on array and is used to loop through each key/value pair in an array. foreach loop – Loops through a block of code for each element in array. let’see below simple example.

Step 1: Create a controller

First, let’s create a controller that will handle our data and pass it to the view. can use any existing model, but for this example use default User model.

php artisan make:controller UserController
Controller file code:
<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

class UsersController extends Controller
{
   public function index()
   {
       $users = User::all();
       return view('users', compact('users'));
   }
}
Step 2: Define a route

Next define a route in the routes/web.php file that will link to the controller method.

use App\Http\Controllers\UsersController;

Route::get('/users', [UsersController::class, 'index']);
Step 3: Laravel blade foreach loop example
Blade file code:
<!DOCTYPE html>
<html>
<head>
    <title>Laravel blade foreach loop example - Webstuffsolution</title>
</head>

<body>
<ul>
@foreach ($users as $user)
  <li>{{ $user->id }}</li>
  <li>{{ $user->name }}</li>
@endforeach
</ul>
</body>
</html>
Using the loop variable inside foreach loop in laravel

$loop the variable is used inside the foreach loop to access useful data like name, email, count, index etc. Below is the list of use variables.

  1. $loop->index: The index of the loop iteration (starts at 0)
  2. $loop->iteration: The current loop iteration (starts 1)
  3. $loop->ramaining: The iteration remaining in the loop.
  4. $loop->count: The total numbers of items in the array being iterated.
  5. $loop->first: This is the first iteration through the loop.
  6. $loop->last: This is the last iteration through the loop.
  7. $loop->even: This is the even iteration through the loop.
  8. $loop->odd: This is the odd iteration through the loop.
  9. $loop->depth: The nesting level of the current loop.
  10. $loop->parent: When in a nested loop, the parent’s loop variable.

 

I hope this tutorial help you.