Laravel 5 View composer gives me an undefined variable

I am using Laravel 5, I am trying to pass a category variable to a view, but currently I am getting an undefined variable.

Here is the code.

First in config / app.php:

'App\Providers\AppServiceProvider', 

In the application / 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 the store /products.php:

 @include('partials.menu') 

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

thanks

+5
source share
4 answers

Try the following commands

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

sometimes these simple tricks help.

+1
source

I think the c method takes an array as an argument, try this instead!

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

I realized that the problem was from your app/Providers/AppServiceProvider.php .

In your loading method, view::composer designed to receive an array of views to which your composer should apply. those. View::composer(['partials.menu'], function($view) { .. }

See full solution:

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

you need to pass the category class in the request correctly, just change Categories::all() to \App\Categories::all() if you haven't changed the namespace.

0
source

All Articles