Last reviewed: 21 Nov 2026
A pharmacy on our POS SaaS opened month-end invoices and recognised a customer that was not theirs. The web app was fine. The leak lived in a queued GenerateInvoicesJob that ran at 02:00 with no tenant on the container. Invoice::query()->get() had no global scope to apply, so the job emailed tenant 41 a mix of tenant 77's rows. That is what a multi-tenant data isolation failure looks like in a real Laravel SaaS: not a missing tenant_id column, but a code path that never received the tenant.
I have shipped multi-tenant products this way — pharmacy POS, school, and delivery platforms on a shared Laravel codebase. The pattern below is what I now put in on day one. It is the application-level half of isolation. For the database-level choices (shared schema versus schema-per-tenant, and PostgreSQL row-level security), use How to Design a Scalable Multi-Tenant SaaS Database alongside this guide.
What "isolated" has to mean
A tenant must not be able to read, update, delete, export, email, or search another tenant's records — including when the attacker already knows the other tenant's IDs. HTTP controllers are the easy part. The paths that actually break are queued jobs, scheduled commands, cache keys, file paths, search indexes, mail, and any DB::select that bypasses Eloquent.
A safe request path — and the leak that skips it
On a normal request the sequence should be mechanical: resolve the tenant once, bind a TenantContext, let a global scope add WHERE tenant_id = ?, and return only that tenant's rows. The job that blew up our pharmacy report skipped every step after "queue worker starts."
How I diagnose a leak in ten minutes
When a customer says they can see someone else's invoices, I do not start by rewriting the trait. I find the path that ran without TenantContext. On a web request the context should already be bound. In a queue worker, Tinker, or an artisan command it usually is not.
$ php artisan tinker
> app()->bound(App\Support\TenantContext::class)
= false
> App\Models\Invoice::query()->count()
TenantContextMissingException
A tenant-owned query ran without TenantContext.That exception is the fail-closed trait doing its job. Bind a tenant, then watch the SQL. Every tenant-owned query should carry tenant_id in both the statement and the bindings.
> $tenant = App\Models\Tenant::query()->where('domain', 'pharmacy-a.pos.example')->first()
> app()->instance(App\Support\TenantContext::class, new App\Support\TenantContext($tenant))
> app(App\Support\TenantContext::class)->id()
= 41
> DB::listen(fn ($q) => dump($q->sql, $q->bindings));
> App\Models\Invoice::query()->count();
"select count(*) as aggregate from \"invoices\" where \"invoices\".\"tenant_id\" = ?"
[41]
= 1284If the listener prints a query with no tenant_id predicate, that is the leak — usually DB::table(), DB::select(), or a withoutTenant() call. Then compare what the job actually sent with what the database holds:
$ php artisan queue:failed
18 redis default App\Jobs\GenerateInvoicesJob 2026-11-21 02:01:12
SELECT id, tenant_id, invoice_number
FROM invoices
WHERE invoice_number = 'INV-1001';
-- id 8821 | tenant_id 41 | INV-1001
-- id 9104 | tenant_id 77 | INV-1001Two rows, two tenants, one invoice number. If the failed job's payload has no tenantId, or the export contains both IDs, you have the same bug we hit on the pharmacy report. Fix the job before you touch the HTTP middleware — the request path was probably already safe.
Resolve the tenant once, in one place
Identify the tenant in middleware from the subdomain, a custom domain, or the authenticated user's membership — then stop guessing. Bind a small context object so the rest of the app never reaches back to the request.
final class TenantContext
{
public function __construct(public Tenant $tenant) {}
public function id(): int
{
return $this->tenant->id;
}
}
final class IdentifyTenant
{
public function handle(Request $request, Closure $next): Response
{
$tenant = Tenant::query()
->where('domain', $request->getHost())
->firstOrFail();
app()->instance(TenantContext::class, new TenantContext($tenant));
return $next($request);
}
}Register that middleware on the tenant HTTP group. After it runs, app(TenantContext::class)->id() is the only number the rest of the request should need. Do not pass $request->user()->tenant_id through every controller — that is how a later job, which has no user, "forgets."
Scope every query by default, and fail closed
A BelongsToTenant trait should add a global scope and should also set tenant_id on create. If the context is missing, I now fail closed in web and queue code. Silent "no scope" behaviour is what let that invoice job leak.
trait BelongsToTenant
{
protected static function bootBelongsToTenant(): void
{
static::addGlobalScope('tenant', function (Builder $builder) {
if (! app()->bound(TenantContext::class)) {
throw new TenantContextMissingException(
'A tenant-owned query ran without TenantContext.'
);
}
$builder->where(
$builder->getModel()->getTable().'.tenant_id',
app(TenantContext::class)->id()
);
});
static::creating(function (Model $model) {
if (! empty($model->tenant_id)) {
return;
}
if (! app()->bound(TenantContext::class)) {
throw new TenantContextMissingException(
'Tried to create a tenant-owned row without TenantContext.'
);
}
$model->tenant_id = app(TenantContext::class)->id();
});
}
public function scopeWithoutTenant(Builder $builder): Builder
{
return $builder->withoutGlobalScope('tenant');
}
}Use Invoice::withoutTenant() only in clearly named super-admin or migration code, and review every call. Unique indexes should be tenant-aware, otherwise two pharmacies cannot both have invoice INV-1001:
$table->foreignId('tenant_id')->constrained()->cascadeOnDelete();
$table->string('invoice_number');
$table->unique(['tenant_id', 'invoice_number']);Route binding and policies still matter
Once the global scope is on the model, Invoice::query()->whereKey($id)->firstOrFail() already 404s for another tenant's ID. Keep it that way in explicit route bindings so nobody later writes Invoice::withoutTenant()->find($id) to "make the route work."
Route::bind('invoice', function (string $value) {
return Invoice::query()->whereKey($value)->firstOrFail();
});A policy that also compares $invoice->tenant_id to the current context is cheap insurance, and it documents the rule for the next developer. If someone can still reach another tenant's record by guessing an ID, you have an IDOR — I walk through the request-level version of that bug in How to Prevent IDOR Vulnerabilities.
Restore the tenant in every job, listener and command
This is the fix I applied to the pharmacy report. Pass the tenant ID into the job at dispatch time, and restore TenantContext in job middleware before handle() touches the database.
final class SetTenantContext
{
public function __construct(public int $tenantId) {}
public function handle(object $job, Closure $next): mixed
{
$tenant = Tenant::query()->findOrFail($this->tenantId);
app()->instance(TenantContext::class, new TenantContext($tenant));
return $next($job);
}
}
final class GenerateInvoicesJob implements ShouldQueue
{
public function __construct(public int $tenantId) {}
public function middleware(): array
{
return [new SetTenantContext($this->tenantId)];
}
public function handle(): void
{
Invoice::query()->each(function (Invoice $invoice) {
// Already limited to $this->tenantId.
});
}
}
// When the HTTP request still has context:
GenerateInvoicesJob::dispatch(app(TenantContext::class)->id());For artisan commands and the scheduler, do the same: accept --tenant=, or loop Tenant::query()->each and bind context inside the loop. A nightly command that runs Invoice::query()->count() with no context should now throw TenantContextMissingException instead of silently summing every tenant.
$schedule->command('invoices:generate --tenant=all')->dailyAt('02:00');Cache, files, search and mail leak just as easily
A shared key such as dashboard_stats or a file path such as invoices/INV-1001.pdf will serve tenant B's data to tenant A. Prefix everything with the tenant ID.
$key = 't:'.app(TenantContext::class)->id().':dashboard-stats';
$stats = Cache::remember($key, 60, fn () => DashboardStats::forCurrentTenant());
$path = 'tenants/'.app(TenantContext::class)->id().'/invoices/'.$filename;
Storage::put($path, $contents);The same rule applies to Scout or Meilisearch filters, Redis keys, broadcast channels (tenant.{id}.invoices), and mail views. If the cache, disk, or channel name would collide when two tenants use the same invoice number, it is not isolated.
Raw SQL and withoutTenant() are deliberate exits
Global scopes do not apply to DB::select, DB::table, or a query builder you constructed without the model. Write the predicate yourself, or do not use raw SQL.
$tenantId = app(TenantContext::class)->id();
$rows = DB::select(
'select id, total from invoices where tenant_id = ? and issued_on = ?',
[$tenantId, $date]
);I treat any withoutTenant() or withoutGlobalScope('tenant') as a review flag. The name should appear in a pull request, with a reason, and usually with a test that still proves tenant B cannot get tenant A's row through the public route.
Prove it with two tenants, not a comment
The test that would have caught our invoice leak is short. Create two tenants, act as A, and request B's ID on every surface that can return data: show, index, update, export, and the job output.
public function test_a_tenant_cannot_view_another_tenants_invoice(): void
{
$alpha = Tenant::factory()->create(['domain' => 'alpha.test']);
$beta = Tenant::factory()->create(['domain' => 'beta.test']);
$foreign = Invoice::factory()->create(['tenant_id' => $beta->id]);
$this->get('https://alpha.test/invoices/'.$foreign->id)
->assertNotFound();
}
public function test_invoice_job_does_not_include_other_tenants(): void
{
$alpha = Tenant::factory()->create();
$beta = Tenant::factory()->create();
Invoice::factory()->create(['tenant_id' => $beta->id, 'invoice_number' => 'INV-999']);
(new GenerateInvoicesJob($alpha->id))->handle();
Mail::assertNotSent(InvoiceReadyMail::class, function (InvoiceReadyMail $mail) {
return $mail->invoice->invoice_number === 'INV-999';
});
}If you only test the happy path for tenant A, you have not tested isolation.
Common mistakes I still catch in review
- A global scope that no-ops when
TenantContextis missing, so jobs and commands silently run unscoped. - Dispatching a job with a model that uses
SerializesModelsbut never restoring the tenant before the job reloads it. - Unique indexes on
emailorinvoice_numberwithouttenant_id, which either blocks a second tenant or tempts someone to drop the unique constraint. - Cache keys and storage paths that are global, especially "latest export" files.
Invoice::find($id)in a console command, orDB::table('invoices')with no tenant predicate.- Tests that use a single tenant and never try the other tenant's IDs.
- Relying on the database design alone. Row-level security helps; it does not replace a job that builds a CSV from an unscoped query and then emails it.
Questions I get asked
Is a tenant_id column enough for multi-tenant data isolation?
No. The column is the handle. Isolation is every query, job, cache key, file path and test actually using it. A missing context is more dangerous than a missing column, because the app will still run.
Should I use a package such as stancl/tenancy?
You can. Packages help with database-per-tenant or schema-per-tenant bootstrapping. For a shared-schema Laravel SaaS, a small TenantContext plus a global scope is usually clearer, and you still have to handle jobs, cache and files yourself either way.
What should happen when TenantContext is missing?
In HTTP and queue workers, throw. In a one-off maintenance command, bind the tenant explicitly or call a clearly named withoutTenant() after review. Do not default to "run unscoped."
How do I run a report across all tenants?
Loop tenants and re-bind context for each one, or write a separate reporting connection that is not used by the SaaS request path. Do not remove the global scope in the tenant app "just for this export."
Does this replace row-level security?
No. Application scoping and PostgreSQL RLS complement each other. I still want the database to refuse a forgotten predicate. That design is covered in the multi-tenant database design guide.
About the author. Muhammad Wilayat Shah is a senior full-stack engineer and team lead based in Islamabad, with 13+ years shipping ERP and multi-tenant SaaS products — including pharmacy POS, Campus School ERP, and delivery platforms — on Laravel, React and PostgreSQL. He wrote this after a queued invoice job in a pharmacy SaaS ran with no tenant context and mixed one customer's records into another's report. More at wilayats.com/about.
Last reviewed: 21 Nov 2026




Comments
Join the discussion. Replies load on demand, up to 5 levels.
0 threads
No comments yet
Be the first to start the conversation.