1. Understanding Multi-Tenant Architecture
A multi-tenant system serves multiple organizations (tenants) from a unified application codebase. The fundamental challenge is guaranteeing absolute data isolation between tenants while optimizing infrastructure costs.
2. Database Isolation Strategies
- Single Database with Tenant Scoping: Every table contains a `tenant_id` column. Global query scopes enforce that queries only access the active tenant's records. Highly cost-effective for small to medium scale.
- Multi-Database Architecture: Each tenant has an independent database. Highest security isolation and straightforward per-tenant backups, but requires automated connection switching.
3. Resolving the Active Tenant
Never accept a raw tenant ID from client query parameters. Resolve tenant identity via:
- Verified subdomain routing (e.g. `clinic-a.saas.com`).
- Authenticated user session / JWT claims tied to verified organization memberships.
4. Enforcing Global Query Scopes
Utilize Laravel's `TenantScope` trait on all tenant-owned models. This automatically injects `where('tenant_id', $currentTenantId)` on every `select`, `update`, and `delete` query.
5. Multi-Tenant Role-Based Access Control (RBAC)
Distinguish Super Admins (platform maintenance) from Clinic/Organization Admins and regular users. Permissions must always be validated against the active tenant context.
6. Automated Testing for Cross-Tenant Data Leaks
Write automated feature tests that explicitly instantiate two distinct tenants. Verify that Tenant A receives a 403 Forbidden or 404 Not Found response when attempting to access or mutate Tenant B's resource IDs.