Mastering Foreach() Loops in Laravel 7/8 - A Step-by-Step Guide

 How to use foreach() loop in blade file in Laravel 7/8 with Example

Mastering-Foreach()-Loops-in-Laravel-7/8-A-Step-by-Step-Guide

In this article we will learn how to you use foreach() loop inside your blade file or view file in Laravel 7/8 . Using foreach() loop inside a blade file is almost similar to using foreach() loop in your controller but the basic difference is the syntax . There are some minor syntax changes you have to keep in mind while using foreach() loop inside your blade file .

So let's see an example of using foreach() loop inside your blade file . We will take an example where i will extract all the users data from the database and will render it on the blade file using foreach() loop .

UsersController.php :

Write your code to get data from database which you want to render in your blade file and once you get the data from your database , send that variable to your blade file as shown in the below code .

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\User;

class UsersController extends Controller
{
    public function usersList()
    {
    	$data = User::all();
    	return view('users',compact('data'));
    }
}

users.blade.php :

Now we got the data from the controller in " $data " variable , now it's time to render it on our view file as shown below .

<!DOCTYPE html>
<html>
<head>
	<title>User List</title>
	<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BmbxuPwQa2lc/FVzBcNJ7UAyJxM6wuqIj61tLrc4wSX0szH/Ev+nYRRuWlolflfl" crossorigin="anonymous">
	<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.6.0/dist/umd/popper.min.js" integrity="sha384-KsvD1yqQ1/1+IA7gi3P0tyJcT3vR+NdBTt13hSJ2lnve8agRGXTTyNaBYmCR/Nwi" crossorigin="anonymous"></script>
	<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/js/bootstrap.min.js" integrity="sha384-nsg8ua9HAw1y0W1btsyWgBklPnCUAFLuTMS2G72MMONqmOymq585AcH49TLBQObG" crossorigin="anonymous"></script>
</head>
<body>

	<div class="row">
		<div class="col-12">
			<table class="table">
				<tr>
					<th>ID</th>
					<th>Name</th>
					<th>Email</th>
					<th>Created At</th>
				</tr>
				@foreach($data as $key => $user)

					<tr>
						<td>{{$user->id}}</td>
						<td>{{$user->name}}</td>
						<td>{{$user->email}}</td>
						<td>{{$user->created_at}}</td>
					</tr>

				@endforeach

			</table>
		</div>
	</div>

</body>
</html>

Output :

How to use Foreach() loop in Blade file - Laravel 7/8




Previous Post Next Post

Contact Form