Laravel Blade: How to use Foreach Loop

Laravel Blade: How to use Foreach Loop

This is a quick example of using foreach loop in a laravel blade. A simple and useful example for any laravel 5,6,7,8,9.

Look at an example:

Controller Code :

namespace App\Http\Controllers;
use Illuminate\Http\Request;
class UserController extends Controller

   // index method
   public function index()
        $users =[
    [ 'id' => 1, 'name' => 'Taylor'],
    [ 'id' => 2, 'name' => 'Otwel'],
    [ 'id' => 3, 'name' => 'Maksud'],
    [ 'id' => 4, 'name' => 'Masud'],
        return view('users', compact('users'));


Blade Example :

<!DOCTYPE html>



    <h1>User List</h1>

    <table border="1">
            @foreach ($users as $key => $user)
                    <td>Serial:{{ $loop->iteration }}</td>
                    <td>Id: {{ $user['id'] }}</td>
                    <td> Name: {{ $user['name'] }} </td>






User List

SL ID Name
Serial:1 Id: 1 Name: Taylor
Serial:2 Id: 2 Name: Otwel
Serial:3 Id: 3 Name: Maksud
Serial:4 Id: 4 Name: Masud

Get The latest Coding solutions.

Subscribe to the Email Newsletter