Docs / Architecture / Tenancy
Forget the tenant and the query returns nothing, not everything.
Single database, global tenant scope, and an isolation test suite. Laravel 12 · PHP 8.3+.
app/Tenancy/BelongsToTenant.phpPHP 8.3 · Pest
namespace App\Tenancy;trait BelongsToTenant{ protected static function bootBelongsToTenant(): void { // no current tenant: the query matches nothing static::addGlobalScope(new TenantScope); static::creating(function ($model) { $model->tenant_id ??= tenant()?->id; }); }}it('fails closed without a tenant', function () { Invoice::factory()->for(Tenant::factory())->create(); Tenancy::forget(); expect(Invoice::count())->toBe(0);});
The scope, and a test that tries to get past it
How one request is kept inside its tenant
Request comes inquill.plinthstack.examplehost
Tenant is resolvedBy subdomain or custom domainQuill & Ledger
Tenant scope addedOn every query, automaticallyglobal
Files, cache, queue scopedStorage, cache keys and queued jobsscoped
Isolation suite passesTests try to cross and cannotgreen
php artisan test --testsuite=TenancyPASSED
Tests58 passed
Assertions204
Cross-tenant rows read0
Query without a tenantEmpty
Duration4.37 s
Two ways to resolve
By subdomain or by custom domain, with certificate provisioning notes for both.
Not only the database
File storage, cache keys and queued jobs carry the tenant too.
Proved, not promised
The suite tries to cross the tenant boundary and proves it cannot.