Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 880
Dino Avatar asked May 12 '15 01:05

Dino


2 Answers

Try these commands

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

sometimes, these simple tricks help.

like image 80
Rohit Kapali Avatar answered Oct 12 '22 07:10

Rohit Kapali


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());
    });
}
like image 23
Tochukwu Nkemdilim Avatar answered Oct 12 '22 08:10

Tochukwu Nkemdilim