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


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 .


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>
	<title>User List</title>
	<link href="" rel="stylesheet" integrity="sha384-BmbxuPwQa2lc/FVzBcNJ7UAyJxM6wuqIj61tLrc4wSX0szH/Ev+nYRRuWlolflfl" crossorigin="anonymous">
	<script src="" integrity="sha384-KsvD1yqQ1/1+IA7gi3P0tyJcT3vR+NdBTt13hSJ2lnve8agRGXTTyNaBYmCR/Nwi" crossorigin="anonymous"></script>
	<script src="" integrity="sha384-nsg8ua9HAw1y0W1btsyWgBklPnCUAFLuTMS2G72MMONqmOymq585AcH49TLBQObG" crossorigin="anonymous"></script>

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





Output :

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

Previous Post Next Post

Contact Form