You are viewing the documentation for an older version of this package. You can check the version you are using with the following command:
composer show spatie/laravel-multitenancy
Using tenant specific facades
Facades behave like singletons. They only resolve once, and each use of the facade is against the same instance. For multitenancy, this may be problematic if the underlying instance behind a service, is built using tenant specific configuration.
If you only have a couple of tenant specific facade, we recommend only clearing them when switching a tenant. Here's a task that you could use for this.
namespaceApp\Tenancy\SwitchTasks;
useIlluminate\Support\Facades\Facade;
useIlluminate\Support\Str;
useSpatie\Multitenancy\Models\Tenant;
useSpatie\Multitenancy\Tasks\SwitchTenantTask;
classClearFacadeInstancesTaskimplements SwitchTenantTask
{
publicfunctionmakeCurrent(Tenant $tenant): void
{
// tenant is already current
}
publicfunctionforgetCurrent(): void
{
$facadeClasses = [
// array containing class names of faces you wish to clear
];
collect($facadeClasses)
->each(
fn (string $facade) => $facade::clearResolvedInstance($facade::getFacadeAccessor);
);
}
}
Should you want to clear out all defined facades, you can use this code (provided by Adrian Brown) which will loop through all defined classes.
namespaceApp\Tenancy\SwitchTasks;
useIlluminate\Support\Facades\Facade;
useIlluminate\Support\Str;
useSpatie\Multitenancy\Models\Tenant;
useSpatie\Multitenancy\Tasks\SwitchTenantTask;
classClearFacadeInstancesTaskimplements SwitchTenantTask
{
publicfunctionmakeCurrent(Tenant $tenant): void
{
// tenant is already current
}
publicfunctionforgetCurrent(): void
{
$this->clearFacadeInstancesInTheAppNamespace();
}
protectedfunctionclearFacadeInstancesInTheAppNamespace(): void
{
// Discovers all facades in the App namespace and clears their resolved instance:collect(get_declared_classes())
->filter(fn ($className) => is_subclass_of($className, Facade::class))
->filter(fn ($className) => Str::startsWith($className, 'App') ||Str::startsWith($className, 'Facades\\App'))
->each(fn ($className) => $className::clearResolvedInstance(
$className::getFacadeAccessor()
));
}
}