How to Pass Data to Views in Laravel
Thank you for your continued support.
This article contains advertisements that help fund our operations.
Table Of Contents
This article summarizes how to pass data to views in Laravel.
Introduction
The content in this article remains relevant as of Laravel 11.
For versions prior to Laravel 7, the way of writing routes (web.php
) differs from this article.
However, the main content regarding controller code is still applicable.
How to Pass Data to Views
Controller Code Example
public function index()
{
$users = User::all();
return view('welcome', ['users' => $users]);
}
By writing this code, you can use the variable $users
in resources/views/welcome.blade.php
.
The view('welcome')
method specifies the relative path from resources/views/
, which is the base directory.
The ['users' => $users]
part indicates that users
is the variable name available in welcome.blade.php
, accessible as $users
.
If you use ['a' => $users]
, you would access it as $a
.
This covers the main point, but below I will explain the steps to create a page using this method.
Steps to Use Data in a View
1. Write the Route
routes/web.php
use App\Http\Controllers\HomeController;
Route::get('/', [HomeController::class, 'index']);
For those unfamiliar with routing, refer to → Basic Routing in Laravel 8.
For Laravel 7 and earlier, see → Basic Routing for Laravel 6 and 7: A Starter Guide.
2. Create the Controller
Command:
php artisan make:controller HomeController
This will create app/Http/Controllers/HomeController
.
3. Add Code to the Controller
Here, I’ll use an example of retrieving users
data.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
class HomeController extends Controller
{
public function index()
{
$users = User::all(); // Retrieve data
// Specify resources/views/welcome.blade.php
return view('welcome', ['users' => $users]);
}
}
4. Write the View
resources/views/welcome.blade.php
$users
is a type called a collection, which can be used similarly to an array.
When handling this data, you need to iterate over it using foreach
, for example.
<div>
@foreach($users as $user)
<div>{{ $user->name }}</div>
@endforeach
</div>
→ How to Display Lists with Foreach in Laravel
Alternative Syntax
The line return view('welcome', ['users' => $users]);
can be implemented in other ways as well.
Using compact() (Recommended)
return view('welcome', compact('users'));
I find this method to be the best.
For passing multiple variables:
return view('welcome', compact('users', 'posts'));
Using with
return view('welcome')->with('users', $users);
This method has been necessary for me in some cases involving email functionality.
Conclusion
That's all.
I hope this article is helpful to someone.