Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

lat4732's avatar
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?

0 likes
7 replies
lat4732's avatar
Level 12

@Snapey Not what I need. Thats for each view rendered, no matter in which controller. I need to define it only in a specific controller.

Snapey's avatar

you can specify which views it applies to

but alternatively use view:share in your controller, you will have to call it from each function that needs it

you can't just add a method called boot() and expect it to be called

1 like
Sinnbeck's avatar

The boot method goes in a service provider, not a controller

1 like
sr57's avatar

You can create an helper function footerCategories() and use it globally like a normal helper.

That said, it's probably not a good idea to fetch the db at each request for data that does not change a lot, so you can also write an event listening for change of this data and setup session vars to use globally.

1 like
Snapey's avatar
Snapey
Best Answer
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
lat4732's avatar
Level 12

Well as I can see there is no short way of doing it. I'll use @snapey's suggestion. Thanks to everyone!

Please or to participate in this conversation.