spatie/laravel-multitenancy
Unopinionated multitenancy for Laravel. Detect the current tenant per request and define what happens when switching tenants. Supports single or multiple databases, tenant-aware queued jobs, commands that run per tenant, and easy per-model connection setup.
At the start of each request, the package will try to determine which tenant should be active for the current request. The package ships with a class named DomainTenantFinder that will try to find a Tenant whose domain attribute matches with the hostname of the current request.
In the multitenancy config file, you specify the tenant finder in the tenant_finder key.
// in multitenancy.php
/*
* This class is responsible for determining which tenant should be current
* for the given request.
*
* This class should extend `Spatie\Multitenancy\TenantFinder\TenantFinder`
*
*/
'tenant_finder' => Spatie\Multitenancy\TenantFinder\DomainTenantFinder::class,
If there is a tenant returned by the tenant finder, all configured tasks will be performed on it. After that, the tenant instance will be bound in the container using the currentTenant key.
app('currentTenant') // will return the current tenant or `null`
You can create a tenant finder of your own. A valid tenant finder is any class that extends Spatie\Multitenancy\TenantFinder\TenantFinder. You must implement this abstract method:
abstract public function findForRequest(Request $request): ?IsTenant;
Here's how the default DomainTenantFinder is implemented. The getTenantModel returns an instance of the class specified in the tenant_model key of the multitenancy config file.
namespace Spatie\Multitenancy\TenantFinder;
use Illuminate\Http\Request;
use Spatie\Multitenancy\Contracts\IsTenant;
class DomainTenantFinder extends TenantFinder
{
public function findForRequest(Request $request): ?IsTenant
{
$host = $request->getHost();
return app(IsTenant::class)::whereDomain($host)->first();
}
}
How can I help you explore Laravel packages today?