Reputation: 1457
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
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
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
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
Reputation: 37
i think the method "with" accepts an array as argument, instead try this !
$categories = Categories::all();
$view->with(compact('categories'));
Upvotes: 0