How do I isolate tenant data in Laravel so a bug can’t leak across tenants?
No approach to Laravel tenant data isolation can promise that a bug never leaks data. You can make sure a bug fails closed instead of returning another customer’s rows. In Laravel, that means putting the tenant boundary in the database layer, below everyday application code, and treating Eloquent scopes as a second guard rather than the only one. This page covers where to place that boundary, what still leaks around it, and how to test it.
Quick answer
Laravel tenant data isolation has three common models: a database per tenant, a shared PostgreSQL database with row-level security, or a shared database with Eloquent global scopes alone. The first two survive a forgotten where() clause, provided the request selects the right tenant and the database role cannot bypass the isolation; the third does not. In all three, make queues, cache and file storage tenant-aware. Then test with two tenants that try to read each other’s data.
Why a forgotten tenant filter is the real risk
In a shared-table multi-tenant design, every query has to remember the tenant. One raw query, report export, or admin screen that skips the filter can cause a cross-tenant leak. Another customer’s rows end up on the wrong screen.
Eloquent global scopes help, but they only apply to Eloquent queries. A query written with the DB facade skips them. A developer can also remove them for one query with withoutGlobalScopes(). A protection that any query can switch off will eventually be switched off by mistake.
How to isolate tenant data in Laravel
Step 1: Resolve the tenant from a trusted source
Every other control depends on knowing which tenant the request belongs to. Resolve it early, in middleware, and treat anything the client sends as a hint that still needs proof.
A subdomain, a path segment, a header or a query parameter can all select a tenant, and tenancy packages such as stancl/tenancy support all four. A client-supplied tenant ID only selects a tenant and proves nothing about access. Look the tenant up on the server, then confirm that the authenticated user is a member of it and holds the permissions the action needs. A user who edits the value to another company’s ID should get a 403.
Validate the Host header and domain too. By default Laravel answers requests for any Host header, and it uses that value when it builds absolute URLs. Restrict hosts at the web server, or enable Laravel’s TrustHosts middleware. If tenants use custom domains, give TrustHosts a list or callback of known tenant domains. If no tenant can be resolved, stop the request with a 403 instead of continuing without one.
Step 2: Choose where the boundary lives
Decide this before you write any scope or policy. The choice sets how much damage a single mistake can do.
| Model | What a forgotten where() does | Main cost |
|---|---|---|
| Database per tenant | Cannot reach other databases, provided the connection and credentials are correct | Migrations, backups and credentials multiply per tenant |
| Shared database with PostgreSQL row-level security | Returns only the current tenant’s rows, or nothing | PostgreSQL only; needs a restricted database role |
| Shared database with scopes only | Returns every tenant’s rows | Cheapest to build, highest leak risk |
A database per tenant can give a strong boundary, but only if each request connects to the right database and the database user cannot reach other tenants’ databases. If one shared user can open every tenant database, the boundary rests on connection selection alone. Use separate credentials where you can. Tenancy for Laravel (stancl/tenancy) and Spatie’s laravel-multitenancy can both switch databases per tenant. The Spatie package also supports a single shared database.
Choose a database per tenant when tenants are few, large, or contractually require separation. Choose shared tables with row-level security when you expect many small tenants and run PostgreSQL. MySQL does not provide PostgreSQL-style native row-level security, so shared tables on MySQL rely on scopes and application discipline. No sourced threshold exists for this split, so treat it as a judgment call.
Step 3: Enforce tenant_id with PostgreSQL row-level security
PostgreSQL’s row security policies filter reads and writes at the database level, even when an application query omits the tenant filter. PostgreSQL knows nothing about your Laravel users, though. Your application tells the database which tenant to use, and the policy trusts that value. The documentation states that superusers and roles with BYPASSRLS always bypass the policies. Table owners bypass them too, unless the table uses FORCE ROW LEVEL SECURITY. Whole-table operations such as TRUNCATE are not subject to them.
ALTER TABLE invoices ENABLE ROW LEVEL SECURITY;
ALTER TABLE invoices FORCE ROW LEVEL SECURITY;
CREATE POLICY tenant_isolation ON invoices
USING (tenant_id = NULLIF(current_setting('app.tenant_id', true), '')::bigint)
WITH CHECK (tenant_id = NULLIF(current_setting('app.tenant_id', true), '')::bigint);
The NULLIF wrapper matters. Once a transaction-local setting has been used on a connection, current_setting can return an empty string instead of NULL. An empty string raises a cast error. With NULLIF, an unset tenant becomes NULL and the policy matches no rows. Adjust the cast if your tenant IDs are UUIDs.
Set the tenant inside each transaction from Laravel:
DB::transaction(function () use ($tenant) {
DB::statement("select set_config('app.tenant_id', ?, true)", [(string) $tenant->id]);
// Queries in here only see this tenant's rows.
});
Here, set_config() gives the policy an application-controlled tenant context. The third argument, true, limits the value to the current transaction, so it cannot carry over to the next request on a reused connection. The setting belongs to that connection and transaction, so the transaction and every protected query must run on the same database connection.
This design protects against a forgotten tenant filter. It does not protect against arbitrary SQL execution. A session that can run its own SQL can also call set_config() and pick another tenant, so SQL injection under the same database role defeats it. Use parameterised queries: Laravel’s query builder binds values through PDO, and raw SQL needs explicit bindings. Give the application role only the table privileges it needs, with no superuser or BYPASSRLS attribute. Keep it separate from the owner role that runs migrations, because only the table owner can change row security settings.
Two more trade-offs come with this approach. Tenant work has to happen inside transactions. A blocked read returns no rows instead of an error, and a blocked update changes zero rows, so a missing tenant context looks like missing data. Writes that break the WITH CHECK condition do raise an error. Log all of these cases.
Step 4: Keep Eloquent global scopes as a second layer
A global scope filters every Eloquent query for a model. Laravel’s soft-delete feature uses the same mechanism. Build the scope to fail when the resolved tenant is missing or null, fill tenant_id from the trusted context when a record is created, and block changes to it afterwards. Treat the scope as a second layer. The database boundary from Step 2 or Step 3 is the primary one.
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Scope;
use RuntimeException;
class TenantScope implements Scope
{
public static function currentTenantId(): int|string
{
$tenant = app()->bound('currentTenant') ? app('currentTenant') : null;
if ($tenant === null) {
throw new RuntimeException('No tenant context set.');
}
return $tenant->getKey();
}
public function apply(Builder $builder, Model $model): void
{
$builder->where($model->qualifyColumn('tenant_id'), self::currentTenantId());
}
}
trait BelongsToTenant
{
protected static function bootBelongsToTenant(): void
{
static::addGlobalScope(new TenantScope());
static::creating(function (Model $model) {
$model->tenant_id = TenantScope::currentTenantId();
});
static::updating(function (Model $model) {
if ($model->isDirty('tenant_id')) {
throw new RuntimeException('tenant_id cannot be changed.');
}
});
}
}
Add the BelongsToTenant trait to every tenant-owned model, and keep tenant_id out of $fillable. Here, currentTenant is a container binding that your Step 1 middleware sets. The scope throws when the binding is missing or holds null. The updating guard stops a model save from moving a record to another tenant. With row-level security in place, the WITH CHECK condition blocks the same move at the database.
Model events and scopes only cover Eloquent models. Creating and updating events do not fire for mass updates, mass deletes or inserts made through the query builder or the DB facade. Those paths must set tenant_id themselves. Row-level security and the non-nullable column from Step 6 are the backstop.
Do not add the trait to the model that resolves the tenant, or the scope will throw before the binding exists. Check that the middleware runs before route model binding, or bound models will be looked up without a tenant.
Clean up tenant context when work ends. Queue workers are long-lived processes, so a binding set during one job is still there for the next unless you clear it. Laravel Octane gives each request its own copy of the container, but objects shared between requests, such as the database manager, and any static property can still carry tenant state across requests. Reset anything tenant-specific when a request or job finishes.
Treat every withoutGlobalScopes() call as a review flag. Allow it only in code that is meant to cross tenants, such as an internal admin tool. A CI check that fails the build when the call appears elsewhere is a cheap guard. Raw SQL and DB facade queries need their own explicit tenant condition.
Step 5: Check ownership through relationships and policies
Scoped queries do not stop a user from changing a record ID in a URL. Load records through the current tenant’s relationship instead of querying by ID alone. This example assumes your Tenant model has an orders() relationship:
$order = app('currentTenant')
->orders()
->findOrFail($orderId);
Then add a Laravel policy for the action. This example assumes your User model has a tenants() relationship and checks membership:
public function update(User $user, Order $order): bool
{
return $user->tenants()
->whereKey($order->tenant_id)
->exists();
}
Call $this->authorize('update', $order) in the controller. Tenant membership and user permissions are separate checks. A user can belong to a tenant and still lack the right to edit a record, so enforce both.
Step 6: Add schema constraints as integrity guards
Constraints do not block cross-tenant reads. They stop bad data from being written, which keeps a later bug from making things worse.
- Make
tenant_idnon-nullable on every record that must belong to a tenant. - Use tenant-aware unique constraints, such as a unique pair of
tenant_idandorder_number. - Use composite foreign keys that include
tenant_id, so an order cannot reference another tenant’s customer. The parent table needs a unique key ontenant_idandidfor this to work. - Add
tenant_idto indexes that serve tenant-scoped queries. This improves speed only.
Step 7: Make queues, cache and storage tenant-aware
The database is only one place tenant state lives. Three others commonly leak:
- Queued jobs must carry the tenant that dispatched them and restore it when they run. With Spatie’s laravel-multitenancy v4, set
queues_are_tenant_aware_by_defaultto true, or mark individual jobs with theTenantAwareinterface or thetenant_aware_jobsconfig key. The package then makes the dispatching tenant current inside the job and restores the surrounding code’s previous tenant afterwards. A job that is not tenant-aware runs without a current tenant, so it must make no assumptions about one. The Spatie v4 documentation covers the edge cases. Without a package, pass the tenant ID in the job and set the context at the start ofhandle(). - Cache keys need a tenant prefix, such as
tenant:10:ordersinstead oforders. Without one, tenant A’s cached list can be served to tenant B. - File paths need a per-tenant prefix, such as
tenants/10/invoices/. A folder name is not access control, so verify ownership before you serve, delete or sign a download URL.
Scheduled commands and search indexes follow the same rule. Run them per tenant, or store the tenant ID with every record.
Step 8: Test for leaks with two tenants
Untested isolation is only an assumption. Write these tests once and run them on every build:
- Two-tenant fixtures: create tenants A and B with overlapping data and act as A. Assert that none of B’s IDs appear in any list, search, export or API response.
- Direct ID access: request, update and delete one of B’s records by ID while acting as A. Expect a 404 or 403 each time.
- Created records: assert that a new record gets its tenant ID from the trusted context, even when the request body sends a different one.
- No tenant set: run a query with no tenant context and expect zero rows or an exception, never every row.
- Consecutive tenants: run two requests or jobs for different tenants on the same worker and confirm the second never sees the first tenant’s context.
- Bypass paths: try raw SQL, bulk operations and admin endpoints as a tenant user.
- Production database role: run the suite as the same restricted role production uses. A superuser bypasses row-level security, so the tests would pass for the wrong reason.
What tenant isolation does not protect against
Tenant isolation does not fix broken authorisation inside a tenant. A regular user who can open admin-only records still needs the policies from Step 5. SQL injection under the application’s database role defeats the session-variable approach in Step 3. Backups, analytics exports and a leaked superuser credential sit outside these steps entirely.
Which approach should you pick?
For a new product on PostgreSQL with many small tenants, shared tables with row-level security is a reasonable default. Keep global scopes as a second layer. If tenants are large, regulated, or require contractual separation, a database per tenant is usually safer, provided connections and credentials are set up correctly. The extra operational work is the price.
If you are weighing these options for a build, our team can review tenant isolation as part of a Laravel development engagement.
Related Answers
Still need help?
Questions about tenant isolation in Laravel?
If you're weighing a database per tenant against row-level security, we're happy to walk through what your setup needs and what your options are.
