I have a Laravel v10.x multitenancy application, I’m using stancl/tenancy: ^3.8
with multiple database and InitializeTenancyByDomain
middleware.
In partical terms it’s working fine, but when analyzing the db queries being done in more detail,
controler construct method:
DB::listen(function($query) {
Log::info(
$query->sql,
$query->bindings,
$query->time
);
});
I’m seeing in my logs a lots of (30+ times, for some routes):
select * from `domains` where `domains`.`tenant_id` = ? and `domains`.`tenant_id` is not null limit 1
When In fact I’m calling this route only twice, one non ajax, and other ajax. I can see this in the browser network tab.
So this query being done only twice is the expected.
My assumption at first was that the tenant()
helper isn’t cached (and I’m using it a lot during the request lifetime) in any way, so I tried to cache it extending InitializeTenancyByDomain
class/middleware:
class CustomInitializeTenancyByDomain extends InitializeTenancyByDomain
{
protected $tenantResolver;
public function __construct(DomainTenantResolver $tenantResolver)
{
$this->tenantResolver = $tenantResolver;
}
public function handle($request, Closure $next)
{
$hostname = request()->getHost();
$tenant = $this->getTenant($hostname);
if (! $tenant) {
throw new TenantCouldNotBeIdentifiedException($hostname);
}
tenancy()->initialize($tenant);
return $next($request);
}
protected function getTenant($hostname)
{
Log::info('Getting tenant');
return Cache::remember("tenant_for_domain_{$hostname}", 60, function () use ($hostname) {
return $this->tenantResolver->resolve($hostname);
});
}
}
Also didn’t work because I just the output of the Log::info('Getting tenant');
once, and the queries are still being made.
Some notes: already tried also https://tenancyforlaravel.com/docs/v3/cached-lookup/ , but it not working also, it might be because I’m not using redis cache (no redis in my system).