tenancy-docs/source/docs/v3/cached-lookup.blade.md
Jori Stein 1aff003b27
Cache invalidation solution + note
Because I started to use the cache lookup recently, I've had some issues with the cache invalidation.

I though of sharing the solutions in the documentation:
- Added a solution how to invalidate the cache.

- Added a note/warning to invalidate the cache before  if you intend to update the domain name. Otherwise the invalidate cache will not work as the key will have changed because of the new domain name.
2022-12-21 23:56:58 -05:00

1.5 KiB

title extends section
Cached tenant lookup _layouts.documentation content

Cached lookup

If you're using multiple databases, you may want to avoid making a query to the central database on each tenant request — for tenant identification. Even though the queries are very simple, the app has to establish a connection with the central database which is expensive.

To avoid this, you may enable caching on the tenant resolvers (all in the Stancl\Tenancy\Resolvers namespace):

  • DomainTenantResolver (also used for subdomain identification)
  • PathTenantResolver
  • RequestDataTenantResolver

On each of these classes, you may set the following static properties:

// TenancyServiceProvider::boot()

use Stancl\Tenancy\Resolvers;

 // enable cache
DomainTenantResolver::$shouldCache = true;

// seconds, 3600 is the default value
DomainTenantResolver::$cacheTTL = 3600;

// specify some cache store
// null resolves to the default cache store
DomainTenantResolver::$cacheStore = 'redis';

Cache invalidation

Updating and saving a Tenant model's attributes will cause the cached entry for this model to be invalidated when DomainTenantResolver::$shouldCache is set to true.

You may invalidate the cache by calling :

app(\Stancl\Tenancy\Resolvers\DomainTenantResolver::class)->invalidateCache($tenant);

Note: When using the domain identification, the key of the cache contains the name of the domain. Make sure to invalidate the cache before making any changes if you intend to update the domain name.