spatie/laravel-multitenancy
Unopinionated multitenancy for Laravel. Detect the current tenant per request and run configurable tasks when switching tenants. Supports single or multiple databases, tenant-aware queued jobs, per-tenant Artisan commands, and easy model connection handling.
IsTenant, SwitchTenantTask) enables custom tenant models, finders, and tasks without forking the package. This is critical for edge cases (e.g., tenant-specific configurations, dynamic database schemas).Spatie\Multitenancy\Middleware\ResolveCurrentTenant), allowing seamless insertion into Laravel’s pipeline. Existing middleware (e.g., auth, CORS) can coexist without conflicts.tenant_connection configuration to dynamically switch database connections per request.TenantAware, NotTenantAware) or config flags, reducing boilerplate for background processing. Closure support ensures flexibility for dynamic tenant contexts.DomainTenantFinder). For high-traffic landlord routes (e.g., /admin), this adds latency. Mitigation: Cache tenant lookups or use a faster resolver (e.g., Redis-based).Cache, Mail) may retain stale instances across tenant switches. Requires explicit clearing (e.g., via SwitchTenantTask).CurrentTenantCouldNotBeDeterminedInTenantAwareJob) need retry logic or fallback handling.tenant_id foreign keys), while separate databases need connection management. Hybrid approaches may complicate deployments.User::all()) must be updated to scope by tenant (e.g., User::where('tenant_id', $tenant->id)).tenant_id to logs)? The package lacks built-in tenant context in logs.use Spatie\Multitenancy\Traits\HasTenants).tenant_connection config). Requires a tenants table with connection details (e.g., database, host)..env) to resolve tenants.composer require spatie/laravel-multitenancy.php artisan vendor:publish --provider="Spatie\Multitenancy\MultitenancyServiceProvider".tenant_model, tenant_finder, and database connections in config/multitenancy.php.app/Http/Kernel.php:
protected $middlewareGroups = [
'web' => [
// ...
\Spatie\Multitenancy\Middleware\ResolveCurrentTenant::class,
],
];
app/Models/Tenant.php) with IsTenant contract.tenant_id to pivot tables or use HasTenants trait.tenants table with connection details and configure tenant_connection in the config.queues_are_tenant_aware_by_default).SwitchTenantTask.app(IsTenant::class)->id).laravel_mt_landlord, laravel_mt_tenant_*) as a baseline.Auth::user()) works if the users table includes tenant_id. Use Spatie\Multitenancy\Traits\HasTenants for models.app('currentTenant').app(IsTenant::class)->stripe_key.Mail::tenant($tenant->mailer))./admin/tenants).Tenant::all() and manual tenant switching ($tenant->makeCurrent()).ResolveCurrentTenant middleware to web routes.app('currentTenant') for tenant-specific data.Log::withContext(['tenant_id' => app('currentTenant')?->id])).tenant->queue_connection) and validate via `SwitchTenantHow can I help you explore Laravel packages today?