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

dorqa95's avatar
Level 12

Blade directive variable with only one request

Hello!

I would like to get a little help about reducing the database queries to one for the following blade directive calls.

In my views a couple time I call the @admin directive, which described by the following code in BladeServiceProvider:

public function boot()
    {
        Blade::if('admin', function () {
            return auth()->check() && in_array(auth()->user()->role, Role::rolesArray('admin'));
        });
    }

The problem with this is every time I call the directive, it's searchs for the Role database table for the matching roles. I would like to avoid that, and request that data for only once. What should I do?

Thanks for your help!

0 likes
2 replies
kokoshneta's avatar
Level 27

Cache the result of Role::rolesArray() (with or without the parameter, depending on your code and logic) into a static property or variable and then retrieve that instead of calling the database every time. Alternatively, bind the roles as a singleton in the app if you need to access it on most or all pages.

Please or to participate in this conversation.