2

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..

Harout
  • 175
  • 2
  • 3
  • 12
  • This is a step-by-step doc for view::share https://scotch.io/tutorials/sharing-data-between-views-using-laravel-view-composers – Digvijay Jun 30 '20 at 09:26
  • Does this answer your question? [How to pass data to all views in Laravel 5?](https://stackoverflow.com/questions/28608527/how-to-pass-data-to-all-views-in-laravel-5) – OMR Jun 30 '20 at 09:30

3 Answers3

3

You could do something like this in the constructor of your base controller

$categories=Category::all();
View::share('categories', $categories);

Here is more info in the laravel docs

https://laravel.com/docs/7.x/views#sharing-data-with-all-views

bumperbox
  • 10,166
  • 6
  • 43
  • 66
1

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

public function boot()
{
  $categories=Category::all();
  $view->with('categories', $categories);    
}
STA
  • 30,729
  • 8
  • 45
  • 59
0

@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(),
    ]);
    
});
Kurt Friars
  • 3,625
  • 2
  • 16
  • 29