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
Try these commands
composer dump-autoload
or
php artisan cache:clear
or
php artisan config:clear
sometimes, these simple tricks help.
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());
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With