How to use foreach loop in blade using Laravel

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 :

<?php
  
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>
<html>

<head>
    <title></title>
</head>

<body>

    <h1>User List</h1>

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

        </tbody>
    </table>


</body>

</html>

 

Output:

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

Tags : laravel

Related Post

Maksud

Maksud

I am a thinker, not a talker.