Views Laravel 8 Laravel 9 Laravel 10 Laravel 11 Laravel 12

Undefined Variable in Blade View - Laravel Fix

This error occurs when a Blade view references a variable that wasn't passed from the controller.

The Error

Error Message
Undefined variable $variable

Common Causes

  1. 1 Variable not passed to view
  2. 2 Typo in variable name
  3. 3 Variable name mismatch between controller and view
  4. 4 Using compact() incorrectly

Solutions

1

Pass variable to view

PHP
return view('posts.index', [
    'posts' => Post::all(),
]);
2

Use compact() correctly

PHP
$posts = Post::all();
$categories = Category::all();

return view('posts.index', compact('posts', 'categories'));
3

Use null coalescing in view

Blade
{{ $variable ?? 'Default value' }}

@isset($variable)
    {{ $variable }}
@endisset
4

Share data globally with View::share

PHP
// In AppServiceProvider boot()
View::share('appName', config('app.name'));

Need Help With Your Laravel Project?

I specialize in building custom Laravel applications, process automation, and SaaS development. Whether you need to eliminate repetitive tasks or build something from scratch, let's discuss your project.

Currently available for 2-3 new projects

Hafiz Riaz

About Hafiz

Full Stack Developer from Italy. I build web applications with Laravel and Vue.js, and automate business processes. Creator of ReplyGenius, StudyLab, and other SaaS products.

View Portfolio

Related Errors