2

In my Laravel Blade Layout I created files for the header, navigation, footer, etc. Those Files have been @include()d into a layout file, which has a yield('content').

Now, I want to show for example a product in a view. The view however uses the nav.blade.php, which shows categories (loading from the db).

When sending my product data to my view, I get an error, because the nav has no data about categories:

Undefined variable: categories

Is there a possibility to give the nav the data without sending it with every view?

My public function for the product page currently looks like this:

$product = Product::findOrFail($id);
return view('product.single')->with('product', $product);

In order to work it should also send this with it:

$categories = Category::with('subcategories.products.prices', 'subcategories.products.image')->get();

But i don't want to send that with every view.

xTheWolf
  • 1,756
  • 4
  • 18
  • 43
  • If you're not morally against bad code you can just add that line of code in the view where needed. – apokryfos Sep 14 '16 at 08:20
  • maybe you can use view composer for that. https://laravel.com/docs/5.3/views#view-composers – follio Sep 14 '16 at 08:20
  • http://stackoverflow.com/questions/29715813/laravel-5-global-blade-view-variable-available-in-all-templates – anwerj Sep 14 '16 at 08:40

1 Answers1

2

read about View Composers:

View composers are callbacks or class methods that are called when a view is rendered. If you have data that you want to be bound to a view each time that view is rendered, a view composer can help you organize that logic into a single location.

Amir Bar
  • 3,007
  • 2
  • 29
  • 47