How to fix "Undefined variable" error in Laravel?
Issue
When rendering a Laravel Blade view, I get the following error:
ErrorException: Undefined variable: name (View: /resources/views/welcome.blade.php)
or
Undefined variable: user (View: /resources/views/dashboard.blade.php)
Solution
This can happen when a variable used in the Blade template has not been properly passed from the controller. Try the following:
1. Ensure the Variable is Passed from Controller
Check that the variable is included when returning the view:
return view('welcome', ['name' => $name]);
If using compact()
:
return view('welcome', compact('name'));
2. Use @isset or @empty in Blade Templates
If the variable might be missing, use Blade directives to prevent errors:
@isset($name)
<p>Hello, </p>
@endisset
Or:
@empty($name)
<p>No name provided.</p>
@endempty
3. Check Route Controller for Missing Data
Ensure the controller function responsible for rendering the view is correctly passing the expected variables.
4. Check Middleware and Session Variables
If you’re using session data, ensure the variable is set before accessing it:
session(['user' => 'John Doe']);
Then retrieve it in Blade:
{ { session('user') } }
To debug session values, use:
dd(session()->all());
5. Use Default Values in Blade Templates
To prevent errors, assign a default value:
<p>Hello, </p>
This ensures that even if $name
is undefined, the template will not break.
By following these steps, you should be able to resolve the “Undefined variable” error in Laravel.