How to Pass Data to Blade Template in Laravel
In Laravel, you pass data to a Blade template by returning a view with data using
view('viewname', ['key' => 'value']), with() method, or compact() function. This data becomes available as variables inside the Blade template.Syntax
There are three common ways to pass data from a controller to a Blade template:
view('viewname', ['key' => 'value']): Pass an associative array where keys become variable names.view('viewname')->with('key', 'value'): Chain thewithmethod to pass one variable.view('viewname', compact('variableName')): Usecompactto pass variables by their names.
php
return view('greeting', ['name' => 'Alice']); return view('greeting')->with('name', 'Alice'); $name = 'Alice'; return view('greeting', compact('name'));
Example
This example shows a controller passing a user's name to a Blade template, which then displays a greeting message.
php
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; class WelcomeController extends Controller { public function show() { $name = 'Alice'; return view('welcome', compact('name')); } } // resources/views/welcome.blade.php // // <h1>Hello, {{ $name }}!</h1>
Output
<h1>Hello, Alice!</h1>
Common Pitfalls
Common mistakes when passing data to Blade templates include:
- Forgetting to pass data at all, resulting in undefined variables in the template.
- Passing data with incorrect keys that don't match the variable names used in the Blade file.
- Using
compact()with variable names that are not defined or misspelled.
Always ensure the keys or variable names you pass match those you use inside the Blade template.
php
return view('welcome'); // No data passed, $name will be undefined // Correct way: $name = 'Alice'; return view('welcome', compact('name'));
Quick Reference
| Method | Usage | Description |
|---|---|---|
| Array | view('view', ['key' => 'value']) | Pass multiple variables as an associative array. |
| with() | view('view')->with('key', 'value') | Pass a single variable using method chaining. |
| compact() | view('view', compact('var1', 'var2')) | Pass variables by their names as strings. |
Key Takeaways
Pass data to Blade templates by returning a view with an array, with(), or compact().
Keys or variable names you pass must match those used inside the Blade file.
Use compact() for cleaner syntax when passing variables with matching names.
Always check that variables are defined before passing to avoid undefined errors.