How to Fix 'Undefined Variable' Error in Laravel Blade

Laravel throws "Undefined variable" when your Blade template asks for a variable that was never handed to the view. This guide shows the five real causes โ€” a missing controller pass, a typo in compact(), a layout that never received the data, an @include without variables, and a route rendering the wrong view โ€” and the exact fix for each one, plus defensive Blade patterns that stop the error from coming back.

RH Raja HunainAuthor 29 Nov 2026 2 min read 4 views
On this page
Share

Explanation

You open a page and instead of your content you get this:

ErrorException: Undefined variable $products
(View: /var/www/app/resources/views/shop/index.blade.php)

The page worked yesterday. Nothing in the template changed โ€” or maybe it is a brand-new page and it has never worked at all. Either way, the message is telling you something specific, and once you understand it, the fix is usually a one-line change. The error does not mean Blade is broken, and it does not mean your variable is "wrong" โ€” it means the view is asking for a variable that nobody gave it.

A Blade template can only use the variables that were explicitly passed to it when the view was rendered. A variable that exists in your controller, in your model, or in another Blade file does not automatically exist in this one. Laravel keeps each view's scope separate on purpose, so a mistake in one page cannot leak data into another. That separation is exactly what produces this error โ€” and what makes the fix predictable: find where the variable should have entered the view, and put it there.

Cause 1: The controller never passed the variable

This is the cause in most cases. The controller builds the data, then renders the view without it โ€” or renders a different view than the one you are editing.

<?php

namespace App\Http\Controllers;

use App\Models\Product;

class ShopController extends Controller
{
    public function index()
    {
        $products = Product::where('active', true)->get();

        return view('shop.index');
    }
}

The controller fetched $products, but the view() call does not include it. The Blade file then fails on the very first @foreach ($products as $product). The fix is to pass the data as the second argument of view() โ€” return view('shop.index', ['products' => $products]); โ€” and compact() and with() are two other spellings of the same thing:

<?php

return view('shop.index', compact('products'));
return view('shop.index')->with('products', $products);

All three are correct. Pick one style per project and stay with it, because mixing styles is how the next cause creeps in.

Cause 2: The name you passed is not the name you used

A very common version of this error is a typo that your eyes skip over ten times. The controller passes product (singular) while the Blade file loops over $products (plural). Or compact('product') is called while the variable in the controller is actually named $products. compact() is especially sneaky here: if you pass it a name that does not exist as a variable, PHP 8 throws a warning of its own, and the view still ends up without the data.

The rule is simple and worth checking first every time: the array key you pass is the variable name the view receives. If the key is 'products', the view gets $products. Open the controller and the Blade file side by side and compare the names character by character โ€” plural against singular, camelCase against snake_case. Nine times out of ten, this is where the bug lives.

Cause 3: The variable is used in the layout, not in the page

This one confuses people because the controller did pass the variable โ€” to the child view. But the error points at the layout file, for example a sidebar or a navigation menu in layouts/app.blade.php that lists categories on every page.

{{-- resources/views/layouts/app.blade.php --}}
<nav>
    @foreach ($categories as $category)
        <a href="/categories/{{ $category->slug }}">{{ $category->name }}</a>
    @endforeach
</nav>
@yield('content')

When a child view extends this layout, the variables passed to the child are available inside the layout too โ€” but only the variables passed to that child view. A page that never passes $categories will crash the layout, even though the layout itself was never the problem.

There are two proper fixes, both registered once in AppServiceProvider::boot(). If the data belongs on every page, View::share() makes $categories available in every view. If it belongs only to some views, a view composer is the cleaner tool, because it runs only when a matching view is rendered:

<?php

namespace App\Providers;

use App\Models\Category;
use Illuminate\Support\Facades\View;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    public function boot(): void
    {
        // Every view in the app gets $categories
        View::share('categories', Category::orderBy('name')->get());

        // Or only the layout gets it, when it renders
        View::composer('layouts.app', function ($view) {
            $view->with('categories', Category::orderBy('name')->get());
        });
    }
}

The wrong fix is to copy the same compact('categories') line into every controller. It works for a week, then someone adds a new controller, forgets the line, and the error is back on exactly one page.

Cause 4: An included view did not receive the data

Blade's @include inherits the parent view's variables automatically โ€” but only the variables the parent actually has. If you include a partial and the partial needs something extra, you must pass it explicitly:

{{-- This partial needs $product, but the parent never had it --}}
@include('partials.product-card')

{{-- Pass it explicitly instead --}}
@include('partials.product-card', ['product' => $product])

The same applies to Blade components: a component only sees the attributes you give it in the tag. If a component renders $title and you wrote <x-alert /> without a title attribute, you get the same error. Check the component's view for the variable name, then check the tag that renders it.

Cause 5: The route renders a different view than you think

Sometimes the controller is fine and the Blade file is fine, but they never meet. A route points at a different controller method, or a method returns view('shop.list') while you are editing shop/index.blade.php. The page you see in the browser is rendered from a different file than the one you are fixing, so no edit in your file can ever make the variable appear.

Check the route first:

php artisan route:list --name=shop

Then check which method the route calls and which view that method returns. If you have two similar views โ€” index and list, show and detail โ€” this is the first place to look.

Defensive Blade: stop the error from returning

Fixing the cause is the real solution, but templates that deal with optional data should also defend themselves. The null coalescing operator gives a variable a fallback when it is missing:

<p>{{ $user->name ?? 'Guest' }}</p>
<p>{{ $product->description ?? 'No description yet.' }}</p>

@isset renders a block only when the variable exists, which is the right tool for optional sections:

@isset($promo)
    <div class="banner">{{ $promo->title }}</div>
@endisset

And optional() protects you when the variable exists but holds null โ€” a different error, "Attempt to read property on null", that often appears right after you fix the undefined variable one:

<p>{{ optional($user)->name ?? 'Guest' }}</p>

A word of caution: these guards hide the symptom, they do not fix the cause. If a page must have $products to be useful, a guard that silently renders an empty page is worse than the error. Use guards for genuinely optional data, and fix the controller for data the page cannot live without.

A quick checklist

When this error appears, work through the list in order:

  1. Does the controller method for this route pass the variable to view()?
  2. Is the array key exactly the same as the variable name in the Blade file?
  3. Is the variable used in a layout or an @include that never received it?
  4. Does the route actually render the view you are editing?
  5. Is the variable only set inside an if branch that did not run? A variable defined inside a conditional is undefined outside it โ€” move the assignment above the condition or initialise it with a default first.

That fifth item deserves a line of its own, because it is easy to miss:

<?php

if ($request->has('q')) {
    $results = Product::search($request->q)->get();
}

return view('search.index', compact('results'));

If the request has no q parameter, $results never exists and the view crashes. Initialise it before the condition โ€” $results = collect(); โ€” and the template always has something to loop over, even if it is empty.

Frequently asked questions

Why does the error say the variable is undefined when I can see it in my controller? Because the controller and the view are separate scopes. A variable only crosses from one to the other when you pass it in the view() call, share it, or hand it to a composer.

Does compact() or with() matter? No. Both deliver the same data. What matters is that the name matches. compact('products') needs a variable literally named $products in scope at that line. Pick one style and keep it consistent so a mismatch stands out.

How do I pass data to every page without repeating myself? Use View::share() in AppServiceProvider for small, cheap data like navigation categories, or a view composer when the data belongs to specific views. Both are shown above.

What is the difference between "Undefined variable" and "Attempt to read property on null"? The first means the variable was never given to the view. The second means the variable was given, but its value is null, and you tried to read a property from it. Fix the first by passing the variable, the second by checking for null first or using optional().

Conclusion

The "Undefined variable" error in Laravel Blade is almost never a Blade problem. It is a data-passing problem: the view asked for a variable that nobody delivered. Start at the controller for the route that renders the page, confirm the variable is passed and the name matches exactly, then check layouts, includes and components that might be using it without receiving it. Share layout-wide data once from a service provider instead of in every controller, guard genuinely optional data with @isset or ??, and keep the checklist above nearby โ€” the next time this error appears, you will find it in under a minute. When your controller returns JSON instead of a view, How to Create a REST API in Laravel 13 shows the same data-flow thinking in API shape; and if the error is a missing class rather than a missing variable, How to Fix 'Target Class Does Not Exist' Error in Laravel covers that one.

#Laravel13 #Blade #ErrorFix #PHP #WebDevelopment #Laravel #Debugging #ProgrammingTips

Was this helpful? 0 likes Login to like & bookmark
RH

Written by

Raja Hunain

Full Stack Developer at Raja Dev Solutions โ€” writes about real development work, the errors he faced and exactly how he fixed them, plus practical Laravel, PHP, JavaScript and MySQL tutorials.

More about the author

Comments (0)

No comments yet. Be the first to comment.

Leave a comment

Comments are moderated and appear after approval.

Keep reading

Related Errors & Articles

How to Upgrade Laravel 11 to Laravel 13 (Step by Step)
Tutorial Laravel Development 26 Nov 2026 ยท 8 min read

How to Upgrade Laravel 11 to Laravel 13 (Step by Step)

Laravel 11 reached end of life in March 2026, and Composer now refuses to install it at all. This tutorial walks you through upgrading a Laravel 11 project to Laravel 13 in two safe steps โ€” 11 to 12, then 12 to 13 โ€” including the PHP 8.3 requirement, the tinker conflict that blocks the second jump, and how to verify everything still works.