How can i pass Category::all(); to every view

Viewed 153

I will use the category a lot of places in my views to show, is there a way to insert somewhere so that I can use it in every view without getting this error Undefined variable: categories

At the moment i am doing it like this for every view:

$categories=Category::all();
 return view('posts.create',compact('categories'));
$categories=Category::all();
 return view('posts.edit',compact('categories'));

and so on..

3 Answers

You need AppServiceProvider to do that on app\Providers\AppServiceProvider.php :

public function boot()
{
  $categories=Category::all();
  $view->with('categories', $categories);    
}

@bumperbox's solution is good!

An alternative is to add a view composer with the wildcard * in your AppServiceProvider.

View::composer(['*'], function ($view) {
    return $view->with([
        'categories' => Category::all(),
    ]);
    
});
Related