look into view composers
Jan 19, 2022
7
Level 12
What is the best way to share a query for global use in all views for a controller?
Hello everyone!
I need to pass the query below from my controller to the included footer (in every page) without defining it in each controller method. I've tried with defining a boot method in my controller like this:
public function boot() {
$footerCategories = Categories::where("is_top", 1)->orderBy('created_at', 'desc')->limit(5)->get();
view()->share('footerCategories', $footerCategories);
}
and here's the foreach loop in my layouts/footer.blade.php
@foreach($footerCategories as $cat)
@endforeach
but it isn't working. Returning a Undefined variable $footerCategories error. How to make this work?
Level 122
I would explicitly pass it with each view
public function footerCategories()
{
return Categories::where("is_top", 1)->orderBy('created_at', 'desc')->limit(5)->get();
}
in controller method;
//
//
return view('myviewpage',compact('somedata'))
->withFooterCategories($this->footerCategories());
As your controller should not have many methods in it that return a view, this is the simplest, clearest solution.
1 like
Please or to participate in this conversation.