In Laravel’s MVC architecture, the Controller handles the logic and passes data to the View, where it is displayed to the user.
Understanding how to send data from a controller to a view is essential for dynamic web applications — whether you’re showing a list of products, user details, or dashboard stats.
In this guide, you’ll learn 4 different ways to pass data from a controller to a view in Laravel.
with() MethodYou can use the with() method to pass data from a controller to a view.
// app/Http/Controllers/UserController.php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class UserController extends Controller
{
public function index()
{
$name = "Laravel";
return view('users.index')->with('name', $name);
}
}
<!-- resources/views/users/index.blade.php -->
<h2>Welcome, to {{ $name }}!</h2>
Output:
Welcome, to Laravel!
compact() FunctionThe compact() function is a clean and popular way to pass multiple variables to a view.
public function dashboard()
{
$title = "Dashboard";
$users = ['Amit', 'Ravi', 'Sneha'];
return view('dashboard', compact('title', 'users'));
}
You can also pass data as an array directly inside the view() function.
public function about()
{
return view('about', [
'name' => 'Laravel',
'topic' => 'Laravel Tutorials'
]);
}
View::share() Method (Global Data)If you want to share data across all views, use the View::share() method.
This is useful for app-wide variables like site name, footer text, or company info.
You can add it in the AppServiceProvider file.
// app/Providers/AppServiceProvider.php
use Illuminate\Support\Facades\View;
public function boot(): void
{
View::share('siteName', 'WebImageKit');
}
Passing data from a controller to a view in Laravel is simple and flexible.
You can choose any of these methods depending on your project structure and needs.
Use compact() for clean and readable syntax
Use with() for single variables
Use arrays for quick one-time data passing
Use View::share() for global variables
With these techniques, you can efficiently handle data between your Laravel controller and view, making your web app dynamic and powerful.