How to Pass Data to Blade in Laravel

Introduction

One of the most important features of Laravel is its powerful templating system called Blade. Blade allows developers to create dynamic HTML pages by injecting variables, arrays, objects, and entire collections directly into templates. To make Blade work effectively, you must first understand how to pass data from a controller to a view. This process forms the backbone of dynamic web pages, dashboards, user profiles, admin panels, blog pages, e-commerce product pages, and much more.

Laravel provides multiple clean and elegant ways to pass data from the controller layer to the view layer. Whether you are sending a simple string, multiple variables, database results, Eloquent collections, or complex nested arrays, Laravel makes it incredibly simple.

In this long and detailed post, you will learn everything about how data flows from a controller to a Blade file and how Blade templates use that data to display meaningful content.

Understanding the Relationship Between Controllers and Views

To fully understand data passing, you need to first understand the MVC (Model-View-Controller) architecture that Laravel uses.

  • The Controller receives the incoming request, performs some logic, fetches data if necessary, and decides which Blade view to return.
  • The View (Blade file) is responsible for presenting the data passed by the controller in an HTML format.
  • The Model (optional in this context) interacts with the database to retrieve or store data.

The process looks like this:

  1. User visits a URL.
  2. Route calls a specific controller method.
  3. Controller fetches or prepares data.
  4. Controller returns a Blade view and passes data to the view.
  5. Blade renders that data on the screen.

Every dynamic page in Laravel follows this flow.


Basic Data Passing Example

Let’s begin with the simplest example, the one you provided:

Controller

return view('home', ['name' => 'Ali']);

Blade (home.blade.php)

<h2>Hello, {{ $name }}</h2>

This means:

  • The controller sends a variable named name containing the value "Ali" to the Blade view.
  • Blade receives that variable and prints it using {{ $name }}.

This small example is the foundation for all advanced data-passing techniques.


Why Data Passing Is Important

Passing data to Blade enables you to build pages that respond to user inputs, show real-time content, and display results from the database.

For example, you may want to:

  • Show a list of users fetched from a database
  • Display product details on a product page
  • Render a logged-in user’s profile information
  • Generate reports or summaries
  • Show notifications, alerts, or messages
  • Populate form fields with old or existing data

None of these things are possible without sending data from controllers to Blade templates.


Multiple Ways to Pass Data to Blade

Laravel provides several methods to pass data to views. Some are basic, and others are more advanced. In this post, we will cover all of them in detail.

Here are the most common methods:

  1. Using an associative array
  2. Using the compact() function
  3. Using the with() method
  4. Passing data inside route closures
  5. Passing entire objects or collections
  6. Passing nested arrays
  7. Passing data using View Composers
  8. Sharing global variables across all views
  9. Using the view()->share() method
  10. Passing multiple variables at once
  11. Passing data from a model directly
  12. Passing data using sessions and flash messages
  13. Passing data using Blade components

Each method is helpful in a specific scenario.


Passing Data Using an Associative Array

This is the simplest and most commonly used method.

Controller

return view('home', [
'name' =&gt; 'Ali',
'age' =&gt; 25,
'city' =&gt; 'Lahore'
]);

Blade

<p>Name: {{ $name }}</p>
<p>Age: {{ $age }}</p>
<p>City: {{ $city }}</p>

This is perfect for small datasets or when you want to keep the code readable.


Passing Data Using the compact() Function

The compact() function is a native PHP function that creates an array from multiple variables.

Controller

$name = "Ali";
$age = 25;

return view('home', compact('name', 'age'));

Laravel automatically unpacks the compact array and makes the variables available in Blade.

Blade

<p>{{ $name }}</p>
<p>{{ $age }}</p>

This method is cleaner when you already have variables defined in the controller.


Passing Data Using the with() Method

Laravel provides the with() method to chain data.

Controller

return view('home')->with('name', 'Ali');

For multiple variables:

return view('home')
    -&gt;with('name', 'Ali')
    -&gt;with('age', 25);

Blade

<p>{{ $name }}</p>
<p>{{ $age }}</p>

This method is useful for chaining multiple values in a fluent style.


Passing Data From Route Closures

You can pass data directly from route closures without a controller.

Route

Route::get('/home', function () {
return view('home', &#91;'name' =&gt; 'Ali']);
});

Blade

<h2>Hello, {{ $name }}</h2>

This is useful for small projects, static pages, or quick demos.


Passing Arrays to Blade

You can also pass arrays directly.

Controller

$users = ['Ali', 'Asad', 'Ahmed'];

return view('users', ['users' => $users]);

Blade

@foreach($users as $user)
&lt;p&gt;{{ $user }}&lt;/p&gt;
@endforeach

This is extremely common when working with lists and menus.


Passing Associative Arrays to Blade

Controller

$user = [
'name' =&gt; 'Ali',
'email' =&gt; '[email protected]',
'country' =&gt; 'Pakistan'
]; return view('profile', ['user' => $user]);

Blade

<p>Name: {{ $user['name'] }}</p>
<p>Email: {{ $user['email'] }}</p>
<p>Country: {{ $user['country'] }}</p>

This allows you to pass structured data.


Passing Eloquent Models to Blade

Real applications usually pass database results.

Controller

$user = User::find(1);

return view('profile', ['user' => $user]);

Blade

<p>{{ $user->name }}</p>
<p>{{ $user->email }}</p>

Laravel automatically converts Eloquent models into usable objects in the view.


Passing Collections to Blade

Collections are extremely powerful and commonly used for lists.

Controller

$products = Product::all();

return view('products.index', compact('products'));

Blade

@foreach ($products as $product)
&lt;p&gt;{{ $product-&gt;name }} - {{ $product-&gt;price }}&lt;/p&gt;
@endforeach

Collections make it easy to loop and display large amounts of data.


Passing Nested Data Structures

You can pass deeply nested arrays:

Controller

$data = [
'user' =&gt; &#91;
    'name' =&gt; 'Ali',
    'details' =&gt; &#91;
        'age' =&gt; 25,
        'city' =&gt; 'Karachi'
    ]
]
]; return view('details', ['data' => $data]);

Blade

<p>{{ $data['user']['name'] }}</p>
<p>{{ $data['user']['details']['age'] }}</p>
<p>{{ $data['user']['details']['city'] }}</p>

Blade can access nested data using standard PHP array syntax.


Using Global Data Available in All Views with view()->share()

Sometimes you need to send common data to all Blade views:

In AppServiceProvider

public function boot()
{
view()-&gt;share('appName', 'My Laravel App');
}

Blade

<h1>{{ $appName }}</h1>

This is useful for site-wide variables like:

  • App name
  • Logo URL
  • Site tagline
  • Global settings

Passing Data to All Views Using View Composers

View composers allow you to attach data to specific views automatically.

Composer

View::composer('profile', function ($view) {
$view-&gt;with('countries', Country::all());
});

Now the profile.blade.php will always receive $countries automatically.


Passing Data Using Session Variables

Controllers can store data in the session.

Controller

session(['message' => 'Profile updated']);
return redirect()->back();

Blade

@if(session('message'))
&lt;p&gt;{{ session('message') }}&lt;/p&gt;
@endif

This is commonly used for notifications.


Passing Flash Session Data

Flash data lasts for only one request.

Controller

return redirect()->back()->with('status', 'Saved successfully');

Blade

<p>{{ session('status') }}</p>

Flash messages are used widely in real applications.


Passing Data to Blade Components

Modern Laravel uses components extensively.

Controller

$user = User::find(1);

return view('dashboard', compact('user'));

Blade (dashboard.blade)

<x-user-card :user="$user" />

Component View

<p>{{ $user->name }}</p>

Components allow modular and reusable UI blocks.


Passing Default Values to Blade

You can set defaults inside Blade:

{{ $name ?? 'Guest' }}

Or in the controller:

return view('home', ['name' => $name ?? 'Guest']);

Blade’s Data Display Syntax Explained

Blade uses the following syntax to display data:

{{ $variable }}

This automatically escapes HTML. If you want to show raw HTML:

{!! $html !!}

Checking If Data Exists in Blade

@if(isset($name))
&lt;p&gt;{{ $name }}&lt;/p&gt;
@endif

You can also use:

@empty($variable)

@endempty

Mutating or Transforming Data Before Sending to Blade

It’s considered best practice to clean, transform, or format data inside the controller before passing it to the view.

Controller

$price = number_format(1999.99);

return view('product', ['price' => $price]);

Blade

<p>{{ $price }}</p>

Why You Should Avoid Logic Inside Blade Views

Blade is for presentation, not logic. Avoid:

  • Database queries
  • Complex calculations
  • Business logic

Do all heavy work inside the controller and pass clean data to the view.


Real-World Example: Passing Data for a User Dashboard

Controller

$user = Auth::user();
$orders = Order::where('user_id', $user->id)->get();
$notifications = $user->notifications;

return view('dashboard', compact('user', 'orders', 'notifications'));

Blade

<h2>{{ $user->name }}'s Dashboard</h2>

@foreach($orders as $order)
&lt;p&gt;Order #{{ $order-&gt;id }} - {{ $order-&gt;status }}&lt;/p&gt;
@endforeach @foreach($notifications as $note)
&lt;p&gt;{{ $note-&gt;message }}&lt;/p&gt;
@endforeach

This is how real apps pass data.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *