How do you pass data from controller to view?

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.

 1. Using the with() Method

You 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);
    }
}
View FIle
<!-- resources/views/users/index.blade.php -->
<h2>Welcome, to {{ $name }}!</h2>

Output:

Welcome, to Laravel!

2. Using the compact() Function

The 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'));
}

3. Using an Associative Array

You can also pass data as an array directly inside the view() function.

public function about()
{
    return view('about', [
        'name' => 'Laravel',
        'topic' => 'Laravel Tutorials'
    ]);
}

4. Using the 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');
}

Conclusion

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.

Comments