Dino
Dino

Reputation: 1457

Laravel 5 View composer gives me an undefined variable error

I am using Laravel 5, I am trying to output categories variable to a view but currently I am getting an undefined variable error.

Here is the code.

Firstly in config/app.php:

'App\Providers\AppServiceProvider',

In app/Providers/AppServiceProvider.php:

public function boot()
    {
        View::composer('partials.menu', function($view)
        {
            $view->with('categories', Category::all());
        });
    }

In partials/menu.blade.php:

<ul>
    <li>Home</li>
    @foreach($categories as $category)
        <li><a href="/store/category/{!! $category->id !!}">{!! $category->name !!}</a></li>
    @endforeach
    <li>Basket</li>
    <li>Checkout</li>
    <li>Contact Us</li>
</ul>

and in store/products.php:

@include('partials.menu')

The exact error I get is: Undefined variable: categories any help resolving this would be appreciated.

Thanks

Upvotes: 8

Views: 3545

Answers (4)

Rohit Kapali
Rohit Kapali

Reputation: 216

Try these commands

composer dump-autoload
or
php artisan cache:clear
or
php artisan config:clear

sometimes, these simple tricks help.

Upvotes: 6

HM107
HM107

Reputation: 1391

you need to pass the Categories class in the query correctly, just change Categories::all() to \App\Categories::all() assuming you didn't change the namespace.

Upvotes: 0

Tochukwu Nkemdilim
Tochukwu Nkemdilim

Reputation: 108

I figured out the issue was from your app/Providers/AppServiceProvider.php.

In your boot method, view::composer is meant to receive an array of views your composer should apply to. i.e. View::composer(['partials.menu'], function($view) { .. }

See the complete solution:

public function boot()
{
    View::composer(['partials.menu'], function($view)
    {
        $view->with('categories', Category::all());
    });
}

Upvotes: 2

Abdelilah
Abdelilah

Reputation: 37

i think the method "with" accepts an array as argument, instead try this !

$categories = Categories::all();
$view->with(compact('categories'));

Upvotes: 0

Related Questions