A shared-database multi-tenant app keeps every customer's rows in the same tables, separated by a tenant_id column. That's the cheapest way to run SaaS, and the risk is equally simple: one query that forgets where tenant_id = ? and a customer sees someone else's projects, invoices or users. You won't find that bug by clicking around as one tenant. You find it when a customer emails you a screenshot.
The usual advice is "add a global scope". That's the right start, but a global scope on its own leaves several doors open: what happens when no tenant is set, route model binding that runs before the tenant is known, validation rules that query the database directly, the query builder, and rows written without the model. This article closes each of them, then adds the database constraints and tests that prove the isolation holds. If you're still deciding whether a shared database is right for you at all, start with single database versus database per tenant. Everything here was run in a fresh app on the current release, and the full test file is at the end.
Hold the tenant in one scoped object
Every piece of isolation needs to ask "who is the current tenant?", so put the answer in one class instead of scattering auth()->user()->tenant_id calls around the code:
<?php
namespace App\Tenancy;
use App\Models\Tenant;
use RuntimeException;
class CurrentTenant
{
private ?Tenant $tenant = null;
public function set(?Tenant $tenant): void
{
$this->tenant = $tenant;
}
public function get(): ?Tenant
{
return $this->tenant;
}
public function id(): int
{
if ($this->tenant === null) {
throw new RuntimeException('No current tenant. Refusing to run a tenant-scoped query.');
}
return $this->tenant->getKey();
}
/**
* @template TReturn
*
* @param callable(): TReturn $callback
* @return TReturn
*/
public function runAs(Tenant $tenant, callable $callback): mixed
{
$previous = $this->tenant;
$this->tenant = $tenant;
try {
return $callback();
} finally {
$this->tenant = $previous;
}
}
}The important method is id(), and the important thing about it is that it throws. If code asks for the tenant and none is set, the safe answer is an exception, not null. A where tenant_id is null query returns nothing and hides the bug; a missing filter returns everything. Failing closed turns both into a loud error you'll see in development.
runAs() is for code that legitimately works on behalf of a tenant outside a request, such as a console command looping over tenants or a seeder. It restores the previous tenant even when the callback throws.
Register it as a scoped binding, not a singleton:
<?php
namespace App\Providers;
use App\Tenancy\CurrentTenant;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
public function register(): void
{
// One instance per request or queued job, reset between them
// by Octane and by queue workers.
$this->app->scoped(CurrentTenant::class);
}
}A singleton lives as long as the PHP process. Under PHP-FPM that's one request, but under Octane or a queue worker it's thousands, and a singleton would carry tenant A into the next request for tenant B. Scoped instances are flushed between Octane requests and, as the worker source shows, before each job a queue:work daemon processes. That reset is a safety net, not a mechanism: jobs still need to restore their tenant explicitly, which is covered in the post on tenant context in queued jobs.
A global scope that fails closed
<?php
namespace App\Tenancy;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Scope;
class TenantScope implements Scope
{
public function apply(Builder $builder, Model $model): void
{
$builder->where($model->qualifyColumn('tenant_id'), app(CurrentTenant::class)->id());
}
}qualifyColumn() produces projects.tenant_id rather than a bare tenant_id, which matters as soon as a query joins two tenant tables and the column name becomes ambiguous. Because the scope calls id(), a query on a tenant model with no tenant set throws No current tenant. Refusing to run a tenant-scoped query. instead of quietly returning every customer's rows.
Attach the scope and the write-side rules with a trait, so a model opts in with one line:
<?php
namespace App\Models\Concerns;
use App\Models\Tenant;
use App\Tenancy\CurrentTenant;
use App\Tenancy\TenantScope;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use LogicException;
trait BelongsToTenant
{
public static function bootBelongsToTenant(): void
{
static::addGlobalScope(new TenantScope);
static::creating(function (Model $model) {
$current = app(CurrentTenant::class)->id();
if ($model->tenant_id !== null && (int) $model->tenant_id !== $current) {
throw new LogicException('Refusing to create a record for another tenant.');
}
$model->tenant_id = $current;
});
static::updating(function (Model $model) {
if ($model->isDirty('tenant_id')) {
throw new LogicException('A record cannot move between tenants.');
}
});
}
/**
* @return BelongsTo<Tenant, $this>
*/
public function tenant(): BelongsTo
{
return $this->belongsTo(Tenant::class);
}
}Laravel calls boot plus the trait name automatically, so bootBelongsToTenant() runs once per model class. The creating hook fills tenant_id from the current tenant and refuses an explicit value for another tenant, which stops a request field like tenant_id=7 from planting rows elsewhere even if someone adds it to $fillable. The updating hook stops a record moving between tenants through save().
The models themselves stay plain:
<?php
namespace App\Models;
use App\Models\Concerns\BelongsToTenant;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
class Project extends Model
{
use BelongsToTenant;
protected $fillable = ['name'];
/**
* @return HasMany<Task, $this>
*/
public function tasks(): HasMany
{
return $this->hasMany(Task::class);
}
}I checked where the scope applies, because that's where people get surprised. Relationship queries, whereHas() and withCount() all include the related model's scope inside the subquery, so Project::whereHas('tasks') filters both projects.tenant_id and tasks.tenant_id. Mass updates through Eloquent are scoped too: Project::query()->update([...]) only touches the current tenant's rows. But the Eloquent docs point out that mass updates don't fire updating events, so Project::query()->update(['tenant_id' => 2]) would move rows without tripping the guard above. That's one more reason for the database constraints further down.
Identify the tenant before route model binding
Here's a middleware that resolves the tenant from the hostname, and a couple of routes that use it:
<?php
namespace App\Tenancy;
use App\Models\Tenant;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
class IdentifyTenant
{
public function __construct(private CurrentTenant $current)
{
}
public function handle(Request $request, Closure $next): Response
{
$tenant = Tenant::where('domain', $request->getHost())->first();
abort_if($tenant === null, 404);
$this->current->set($tenant);
return $next($request);
}
}<?php
use App\Http\Controllers\TaskController;
use App\Models\Project;
use App\Tenancy\IdentifyTenant;
use Illuminate\Support\Facades\Route;
Route::middleware(IdentifyTenant::class)->group(function () {
Route::get('/projects/{project}', fn (Project $project) => $project);
Route::post('/tasks', [TaskController::class, 'store']);
});With just that, the first request to /projects/1 failed in my test app with a 500 and the "No current tenant" exception. Implicit route model binding is done by the SubstituteBindings middleware in the web group, and it ran before IdentifyTenant, so the binding query hit the scope with no tenant set. The fail-closed scope did its job. A scope that quietly skips the filter when no tenant is set, which is a common way to write one, would have loaded the project of any tenant by ID instead, and that is one of the most common cross-tenant leaks in Laravel apps. The fix is to move tenant identification ahead of binding in bootstrap/app.php:
<?php
use App\Tenancy\IdentifyTenant;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Illuminate\Routing\Middleware\SubstituteBindings;
return Application::configure(basePath: dirname(__DIR__))
->withRouting(
web: __DIR__.'/../routes/web.php',
commands: __DIR__.'/../routes/console.php',
health: '/up',
)
->withMiddleware(function (Middleware $middleware): void {
$middleware->prependToPriorityList(
before: SubstituteBindings::class,
prepend: IdentifyTenant::class,
);
})
->withExceptions(function (Exceptions $exceptions): void {
})->create();Now /projects/{id} for another tenant's project is a plain 404, because the binding query includes tenant_id and finds nothing. That's the behaviour you want: the response is identical to "doesn't exist", so it doesn't confirm that the ID is in use.
Validation rules don't know about your scope
exists and unique run their own queries against the table name you give them, not through your model, so the global scope never applies. A request that creates a task with project_id set to another tenant's project passes a plain exists:projects,id rule, and the task now points across the tenant boundary. Scope the rule explicitly:
<?php
namespace App\Http\Controllers;
use App\Models\Task;
use App\Tenancy\CurrentTenant;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
class TaskController
{
public function store(Request $request, CurrentTenant $tenant): JsonResponse
{
$data = $request->validate([
'project_id' => [
'required',
Rule::exists('projects', 'id')->where('tenant_id', $tenant->id()),
],
'title' => ['required', 'string', 'max:200'],
]);
return response()->json(Task::create($data), 201);
}
}unique needs the same treatment in the other direction: Rule::unique('projects', 'name')->where('tenant_id', $tenant->id()). Without it, tenant A can't name a project "Website" because tenant B already has one, which is a bug and a small information leak at the same time. The single-database guide for stancl/tenancy calls out exactly these two rules for the same reason, so this isn't specific to hand-rolled tenancy.
Everything else that bypasses the scope
Global scopes belong to Eloquent. Anything that doesn't go through an Eloquent model ignores them:
DB::table('projects')andDB::select(). In the test below,DB::table('projects')->count()returns rows for both tenants whileProject::count()returns one. Reports and exports are where these tend to live.Project::insert()andupsert(), which go straight to the query builder and skip thecreatinghook. With aNOT NULLtenant_idcolumn the insert fails withNOT NULL constraint failed: projects.tenant_id, which is the right outcome; make sure the column is never nullable.withoutGlobalScope(TenantScope::class)andwithoutGlobalScopes(). These are legitimate for an internal admin panel or a cross-tenant report, but grep for them in code review and keep them in a handful of clearly named places.- Many-to-many pivot tables, which have no model and so no scope. Give them a
tenant_idcolumn and constrain it like any child table. - Cache keys, file paths and search indexes. A dashboard cached under
dashboard-statsis shared by every tenant; key it as"tenant:{$id}:dashboard-stats".
For raw queries you can't avoid, the rule is simple: every one of them gets an explicit where('tenant_id', app(CurrentTenant::class)->id()), and every one of them gets a test with two tenants.
Make the database refuse cross-tenant rows
Application checks can be skipped. Constraints can't. Two kinds earn their keep in a shared schema:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('tenants', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('domain')->unique();
$table->timestamps();
});
Schema::create('projects', function (Blueprint $table) {
$table->id();
$table->foreignId('tenant_id')->constrained();
$table->string('name');
$table->timestamps();
$table->unique(['tenant_id', 'name']);
// Lets child tables reference (tenant_id, id) as a pair.
$table->unique(['tenant_id', 'id']);
});
Schema::create('tasks', function (Blueprint $table) {
$table->id();
$table->foreignId('tenant_id')->constrained();
$table->unsignedBigInteger('project_id');
$table->string('title');
$table->timestamps();
// A task can only point at a project of the same tenant.
$table->foreign(['tenant_id', 'project_id'])
->references(['tenant_id', 'id'])
->on('projects');
});
}
public function down(): void
{
Schema::dropIfExists('tasks');
Schema::dropIfExists('projects');
Schema::dropIfExists('tenants');
}
};The unique index on (tenant_id, name) makes names unique per tenant rather than globally. The more interesting one is the composite foreign key: tasks(tenant_id, project_id) references projects(tenant_id, id), which requires that (tenant_id, id) pair to be unique on the parent. The result is that a task row can only point at a project of the same tenant. In the test, inserting such a row through DB::table(), bypassing every Eloquent check, fails with a foreign key violation. It costs one extra index per parent table, and it turns the scariest kind of bug, cross-tenant references, into an error at write time.
On PostgreSQL you can go further with row-level security, so the database filters rows by tenant even for raw SQL:
ALTER TABLE projects ENABLE ROW LEVEL SECURITY;
ALTER TABLE projects FORCE ROW LEVEL SECURITY;
CREATE POLICY tenant_isolation ON projects
USING (tenant_id = current_setting('app.tenant_id', true)::bigint);Your middleware then runs DB::statement("select set_config('app.tenant_id', ?, false)", [$tenant->id]) after identifying the tenant. Two warnings from the Postgres docs decide whether this actually protects you. Table owners bypass row security unless the table has FORCE ROW LEVEL SECURITY, and superusers and roles with BYPASSRLS always bypass it, so the app must not connect as a superuser. And the setting lives on the database session, so with a pooler like PgBouncer in transaction mode a session-level setting can follow the connection to another client; pass true as the third argument to set_config so the value only lasts for the current transaction. I haven't run this policy in the sandbox used for this article, which only has SQLite, so treat it as defence in depth on top of the scope, not a replacement for it.
Tests that prove isolation
Isolation is a property of the whole app, so test it the way an attacker would probe it: two tenants, one request, the other tenant's IDs. This file is the one that verified every claim above, and all seven tests pass:
<?php
namespace Tests\Feature;
use App\Models\Project;
use App\Models\Task;
use App\Models\Tenant;
use App\Tenancy\CurrentTenant;
use Illuminate\Database\QueryException;
use Illuminate\Foundation\Http\Middleware\ValidateCsrfToken;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use LogicException;
use RuntimeException;
use Tests\TestCase;
class TenantIsolationTest extends TestCase
{
use RefreshDatabase;
private Tenant $acme;
private Tenant $globex;
protected function setUp(): void
{
parent::setUp();
$this->withoutMiddleware(ValidateCsrfToken::class);
$this->acme = Tenant::create(['name' => 'Acme', 'domain' => 'acme.localhost']);
$this->globex = Tenant::create(['name' => 'Globex', 'domain' => 'globex.localhost']);
}
private function as(Tenant $tenant, callable $callback): mixed
{
return app(CurrentTenant::class)->runAs($tenant, $callback);
}
public function test_queries_only_see_the_current_tenant(): void
{
$this->as($this->acme, fn () => Project::create(['name' => 'Website']));
$this->as($this->globex, fn () => Project::create(['name' => 'Website']));
$this->assertSame(1, $this->as($this->acme, fn () => Project::count()));
$this->assertSame(['Website'], $this->as($this->globex, fn () => Project::pluck('name')->all()));
}
public function test_another_tenants_record_is_a_404(): void
{
$globexProject = $this->as($this->globex, fn () => Project::create(['name' => 'Secret']));
$this->get("http://acme.localhost/projects/{$globexProject->id}")->assertNotFound();
$this->get("http://globex.localhost/projects/{$globexProject->id}")->assertOk();
}
public function test_exists_rule_rejects_another_tenants_id(): void
{
$globexProject = $this->as($this->globex, fn () => Project::create(['name' => 'Secret']));
$this->postJson('http://acme.localhost/tasks', [
'project_id' => $globexProject->id,
'title' => 'Sneaky',
])->assertUnprocessable()->assertJsonValidationErrors('project_id');
}
public function test_queries_without_a_tenant_fail_closed(): void
{
$this->expectException(RuntimeException::class);
$this->expectExceptionMessage('No current tenant');
Project::count();
}
public function test_records_cannot_be_created_for_or_moved_to_another_tenant(): void
{
$this->as($this->acme, function () {
$project = Project::create(['name' => 'Website']);
$project->tenant_id = $this->globex->id;
$this->expectException(LogicException::class);
$project->save();
});
}
public function test_the_database_rejects_a_cross_tenant_foreign_key(): void
{
$globexProject = $this->as($this->globex, fn () => Project::create(['name' => 'Secret']));
$this->expectException(QueryException::class);
DB::table('tasks')->insert([
'tenant_id' => $this->acme->id,
'project_id' => $globexProject->id,
'title' => 'Sneaky',
]);
}
public function test_query_builder_bypasses_the_scope(): void
{
$this->as($this->acme, fn () => Project::create(['name' => 'Website']));
$this->as($this->globex, fn () => Project::create(['name' => 'Website']));
// This is the leak: DB::table() knows nothing about Eloquent scopes.
$this->assertSame(2, $this->as($this->acme, fn () => DB::table('projects')->count()));
}
}The last test is deliberately a "this leaks" test. It documents that the query builder ignores the scope, so nobody on the team assumes otherwise, and it will start failing if you later add database-level enforcement such as row-level security, which is exactly when you'd want to revisit it.
The test above only covers the models you remembered. The one that catches new mistakes checks every model automatically:
<?php
namespace Tests\Feature;
use App\Models\Concerns\BelongsToTenant;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Schema;
use ReflectionClass;
use Tests\TestCase;
class TenantArchitectureTest extends TestCase
{
use RefreshDatabase;
public function test_every_model_with_a_tenant_id_column_is_scoped(): void
{
$checked = 0;
foreach (File::allFiles(app_path('Models')) as $file) {
$class = 'App\\Models\\'.str_replace(['/', '.php'], ['\\', ''], $file->getRelativePathname());
if (! is_subclass_of($class, Model::class) || (new ReflectionClass($class))->isAbstract()) {
continue;
}
if (! Schema::hasColumn((new $class)->getTable(), 'tenant_id')) {
continue;
}
$this->assertContains(
BelongsToTenant::class,
class_uses_recursive($class),
"{$class} has a tenant_id column but doesn't use BelongsToTenant.",
);
$checked++;
}
$this->assertGreaterThan(0, $checked);
}
}I removed use BelongsToTenant from Task to make sure it bites, and it failed with App\Models\Task has a tenant_id column but doesn't use BelongsToTenant. That's the test that saves you six months from now, when someone adds an Invoice model with a tenant_id column and forgets the trait.
Global scopes, withoutGlobalScope() and the mass-update caveat are documented in Laravel's Eloquent guide, and the row security rules in the PostgreSQL row security policies chapter.














