First I would add the view facade before the service provider in ComposerServiceProvider
Jun 13, 2019
7
Level 10
How To Test Why My View-Composer isn't working
I believe I have setup my View-Composer correctly as per the instructions on https://laravel.com/docs/5.8/views#view-composers
I created a new ComposerServiceProvider with php artisan make:provider ComposerServiceProvider. In that file I have
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\View;
class ComposerServiceProvider extends ServiceProvider
{
/**
* Register services.
*
* @return void
*/
public function register()
{
//
}
/**
* Bootstrap services.
*
* @return void
*/
public function boot()
{
View::composer(
'layouts.nav', 'App\Http\View\Composers\CategoryComposer'
);
}
}
Then I registered it in my config/app.php
'providers' => [
/*
* Laravel Framework Service Providers...
*/
App\Providers\ComposerServiceProvider::class,
],
Then in the folder App\Http\View\Composers\ I created a file CategoryComposer.php and in that I have
<?php
namespace App\Http\View\Composers;
use Illuminate\View\View;
use App\Category;
class CategoryComposer
{
/**
* Bind data to the view.
*
* @param View $view
* @return void
*/
public function compose(View $view)
{
$allcategories = Category::all();
$view->with('allcategories', $allcategories);
}
}
Finally in my views/layouts/nav.blade.php file I have
@foreach($allcategories as $category)
<li><a href="/bestof/{{$category->slug}}" class="text-white">{{$category->name}}</a></li>
@endforeach
Yet when I try to look at the page I am getting the error "Undefined variable: allcategories
Am I missing something? How do I even test for what I am missing?
Please or to participate in this conversation.