Skip to content

Keyboard shortcuts

/
Search posts
CtrlK
Search posts (⌘ K on a Mac)
jk
Next / previous section (in a post)
s
Save or unsave this post
f
Focus mode: hide everything but the text
l
Listen: read the post aloud
t
Cycle theme
+−
Larger / smaller text
gh
Go to the blog home
?
Show this help
Esc
Close panels

Shortcuts are ignored while you type in a field.

Multi-tenant Laravel SaaS: the architecture I actually use

Single database or one per tenant? A production-tested multi-tenant setup for Laravel SaaS: global scopes, tenant resolution, queues and the mistakes to avoid.

Illustration of a cut-away building where each floor is a different business, all standing on one glowing database. Headline: One database. Every tenant kept apart.
On this page 5 sections

Every SaaS I’ve built, from the POS to Oxygen LMS, has had to answer the same question on day one: how do we keep each customer’s data separate? Get it wrong and you either leak data between customers or drown in operational complexity.

The three options#

StrategyIsolationOps costGood for
Shared DB, tenant_id columnLogicalLowMost early-stage SaaS
Schema per tenantMediumMediumPostgres shops, moderate tenant counts
Database per tenantStrongHighEnterprise, compliance, noisy neighbours
DecisionAccepted

Start with a shared database and a tenant_id column

Context. Small team, hundreds of tenants expected, low budget, fast iteration needed.

Decision. One MySQL database; every tenant-owned table has an indexed tenant_id; isolation enforced in the application layer with a global scope.

Consequences. Cheap and simple. The cost is discipline: every query must be scoped, so we enforce it automatically and test it.

Project layout#

  • app/
    • Tenancy/
      • TenantContext.php
      • BelongsToTenant.php
      • TenantScope.php
    • Http/Middleware/
      • ResolveTenant.php
    • Models/
      • Tenant.php
      • Student.php
  • database/migrations/
  • tests/Feature/
    • TenantIsolationTest.php

Step by step#

  1. Hold the current tenant in one place

    A tiny singleton that knows who the current tenant is. Everything else asks it.

    app/Tenancy/TenantContext.php
    php
    final class TenantContext
    {
        private ?Tenant $tenant = null;
     
        public function set(Tenant $tenant): void { $this->tenant = $tenant; }
     
        public function get(): ?Tenant { return $this->tenant; }
     
        public function id(): ?int { return $this->tenant?->id; }
    }

    Register it as a singleton in a service provider: $this->app->singleton(TenantContext::class);

  2. Resolve the tenant from the request

    I use subdomains (school-a.oxygenlms.com). Resolve once per request in middleware and fail closed if the tenant is unknown.

    app/Http/Middleware/ResolveTenant.php
    php
    public function handle(Request $request, Closure $next)
    {
        $sub = explode('.', $request->getHost())[0];
     
        $tenant = Tenant::query()
            ->where('subdomain', $sub)
            ->where('active', true)
            ->firstOrFail(); // fail closed: never fall back to "no tenant"
     
        app(TenantContext::class)->set($tenant);
     
        return $next($request);
    }
  3. Scope every query automatically

    A global scope plus a trait means developers can’t forget the where tenant_id = ? clause.

    php
    trait BelongsToTenant
    {
        protected static function bootBelongsToTenant(): void
        {
            static::addGlobalScope(new TenantScope);
     
            static::creating(function ($model) {
                $model->tenant_id ??= app(TenantContext::class)->id()
                    ?? throw new LogicException('No tenant in context');
            });
        }
    }
  4. Carry the tenant into queued jobs

    Queues are where tenancy bugs hide. A job runs in a different process, so the context is empty. Store the tenant ID on the job and restore it before handle().

    app/Jobs/SendFeeReminders.php
    php
    class SendFeeReminders implements ShouldQueue
    {
        public function __construct(public int $tenantId) {}
     
        public function handle(TenantContext $ctx): void
        {
            $ctx->set(Tenant::findOrFail($this->tenantId));
            // ... scoped queries are safe from here
        }
    }
  5. Prove isolation with a test

    This is the most important test in the codebase. It runs on every push.

    tests/Feature/TenantIsolationTest.php
    php
    it('never returns another tenant’s students', function () {
        [$a, $b] = Tenant::factory()->count(2)->create();
        Student::factory()->for($b)->create();
     
        app(TenantContext::class)->set($a);
     
        expect(Student::count())->toBe(0);
    });

Indexes matter more than you think#

With a shared database, almost every query filters by tenant_id first. Put it at the front of your composite indexes:

sql
-- good: matches "where tenant_id = ? and class_id = ? order by name"
CREATE INDEX students_tenant_class_name ON students (tenant_id, class_id, name);

When I’d choose a database per tenant#

Signals that it’s time to move to stronger isolation
  • A customer contract requires physical data separation or data residency.
  • One tenant is so large that it slows everyone else down (noisy neighbour).
  • You need per-tenant backups and restores as a product feature.

Because every model already carries tenant_id, moving a large tenant to its own database later is a data migration, not a rewrite.

Questions readers ask

Should a Laravel SaaS use one database or a database per tenant?

For most early SaaS products, one database with a tenant_id column enforced by a global scope is simpler to run, cheaper to host and easy to migrate later.

When should you move to a database per tenant?

When a contract requires physical separation or data residency, when one tenant is large enough to slow everyone else down, or when per-tenant backups and restores are a product feature.

Where do multi-tenant data leaks usually happen?

In queued jobs and raw queries, where the global scope or tenant context may be missing. Fail closed, so no tenant means no data, and test those paths explicitly.