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

lat4732's avatar
Level 12

Prevent dublicate query

Hey!

I have this in my AppServiceProvider

Blade::if('hasCompany', function () {
return auth()->check() && Companies::where('user_id', auth()->user()->id)->exists();
});

Blade::if('missingCompany', function () {
return auth()->check() && Companies::where('user_id', auth()->user()->id)->doesntExist();
});

But everytime I use @hasCompany or missingCompany it generates a new query to the database to check if company exists/doesn't exist.

viz1

How can I restructure these lines of code to prevent that?

0 likes
2 replies
Sinnbeck's avatar
Sinnbeck
Best Answer
Level 102

Load the companies on the user model, and pass it in. Here we load the count as that is cheaper than loading all companies (unless you need those)

$user->loadCount('companies');

and then the check needs the user

Blade::if('hasCompany', function ($user) {
return $user && $user->companies_count > 0;
});
Niush's avatar
class AppServiceProvider extends ServiceProvider
{
    public bool $hasCompany;

    public function boot()
    {
        Blade::if('hasCompany', function () {
            return $this->hasCompany ?? ($this->hasCompany = Companies::where('user_id', auth()->user()->id)->exists());
        });

        Blade::if('missingCompany', function () {
            return !(return $this->hasCompany ?? ($this->hasCompany = Companies::where('user_id', auth()->user()->id)->exists());
        });
    }
}

Please or to participate in this conversation.