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.

How can I restructure these lines of code to prevent that?
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;
});
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.