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 queues/jobs, per-tenant artisan commands, and easy model connection switching.
tenant1.app.com with resilient background tasks).tenant1-jobs:default) for granular control over job routing.*"This update fixes a critical gap in multi-tenant SaaS reliability: job retries now resolve tenant context from payload data, ensuring failed background tasks (e.g., emails, payments) always run in the correct tenant. For example, if
tenant1.app.com’s invoice generation fails, the retry will automatically targettenant1’s database/queue—no more race conditions or data leaks.ROI Highlights (Updated):
- Dev Time Saved: ~1–2 months less custom retry logic for async workflows.
- Scalability: Handles 100+ tenants with resilient job retries.
- Cost: Free (MIT license) with optional Spatie sponsorship.
- Risk Reduction: Eliminates tenant context loss in failed jobs (e.g., GDPR compliance, financial transactions).
Trade-off: We’ll still need to define how tenant data is embedded in job payloads (e.g.,
tenant_idfield), but the package handles the retry resolution."*
*"New in 4.1.3: Tenant resolution from payload context during job retries. Here’s how we’ll leverage it:
- Job Payload Design: Ensure jobs include
tenant_idortenant_keyin their payload (e.g.,SendInvoiceJobwithtenant_id).- Retry Safety: Failed jobs (e.g.,
SendInvoiceJob::failed()) will auto-resolve the tenant from the payload, preventing context loss.- Testing: Validate retries with:
Tenant::forget(); // Simulate lost context $job->release(); // Retry should resolve tenant from payloadWhy This Matters:
- No More Silent Failures: Retries now work even if tenant context is lost mid-execution.
- Audit Trail: Failed jobs log with correct tenant context (critical for compliance).
- Backward Compatible: Existing tenant resolution (domains, subdirectories) still works.
Next Steps:
- Audit job payloads to include
tenant_id(e.g.,SendEmailJob,ProcessPaymentJob).- Test retry workflows with
Tenant::forget()to simulate edge cases.- Document payload requirements for new jobs (e.g., ‘All async jobs must include
tenant_id’)."*
Key Trade-offs (Updated):
| Pro | Con |
|---|---|
| Resilient job retries | Requires tenant_id in payloads |
| Saves 1–2 months of dev time | Limited to Laravel/PHP |
| Tenant-aware queues/jobs | PHP 8.2+/Laravel 11+ required |
| MIT license (no vendor lock-in) | Custom payload parsing needed |
How can I help you explore Laravel packages today?