The question "how do we isolate data between customers" comes up early in any B2B SaaS, and whatever answer gets picked for the first customer shapes the architecture for the next two years. Changing multi-tenancy strategy after the fact, once a hundred tenants are already in production, is a migration project in its own right, not a refactor. Better to compare the options seriously up front than to ship the first one that compiles.

The concrete problem

A SaaS product for accounting firms or real estate agencies needs to guarantee that tenant A can never, not even through an application bug, see a row of tenant B's data. Three architectures answer this in Laravel, with very different guarantees and operational costs: one database per tenant, one PostgreSQL schema per tenant, or a shared tenant_id column across common tables.

The three strategies and how each one works

One database per tenant

Each tenant gets its own database. Laravel resolves the connection dynamically based on the current tenant, typically identified by subdomain or header.

// Resolve the connection based on the current tenant
class TenantDatabaseMiddleware
{
    public function handle(Request $request, Closure $next)
    {
        $tenant = Tenant::where('domain', $request->getHost())->firstOrFail();

        config([
            'database.connections.tenant.database' => $tenant->database_name,
        ]);
        DB::purge('tenant');
        DB::setDefaultConnection('tenant');

        return $next($request);
    }
}

Isolation is guaranteed by the database engine itself: a poorly written query that forgets a WHERE tenant_id = ? cannot physically return another tenant's data, because it is not in the same database. This is the strongest guarantee of the three options.

The cost: migrations have to run against N databases, connection pooling has to be managed dynamically (risk of connection leaks if DB::purge() is forgotten), and cross-tenant queries (global reporting, centralized billing) become noticeably more complex, since they require aggregating across separate databases.

One PostgreSQL schema per tenant

Same logical isolation principle, but inside a single PostgreSQL instance, using search_path.

class TenantSchemaMiddleware
{
    public function handle(Request $request, Closure $next)
    {
        $tenant = Tenant::where('domain', $request->getHost())->firstOrFail();

        DB::statement("SET search_path TO \"{$tenant->schema_name}\", public");

        return $next($request);
    }
}
-- Creating a new tenant: a schema plus a migration run inside it
CREATE SCHEMA tenant_acme;
# Migration executed within the tenant's schema context
php artisan tenants:migrate --schema=tenant_acme

This approach keeps a single database instance to administer (backups, monitoring, PostgreSQL upgrades) while keeping strong logical isolation. It is a solid middle ground between robustness and operational cost, but it is PostgreSQL-specific (MySQL has no exact equivalent to search_path) and demands care: a search_path that is not reset between requests on a reused connection pool can leak one tenant's data into another's response. The search_path must be reset on every incoming request, never only once at connection time.

Shared tenant_id column

All data lives in the same tables, with a tenant_id column and a filter applied systematically.

// Global scope applied automatically on every Eloquent query
class TenantScope implements Scope
{
    public function apply(Builder $builder, Model $model): void
    {
        if ($tenantId = app('currentTenant')?->id) {
            $builder->where($model->getTable() . '.tenant_id', $tenantId);
        }
    }
}

class Invoice extends Model
{
    protected static function booted(): void
    {
        static::addGlobalScope(new TenantScope);

        static::creating(function (Invoice $invoice) {
            $invoice->tenant_id = app('currentTenant')->id;
        });
    }
}

This is the cheapest option to operate (one database, one migration schema, one connection pool) and the simplest for cross-tenant reporting. The downside: isolation depends entirely on application discipline. A Model::query() call that bypasses the global scope, a raw SQL query (DB::table()) without an explicit filter, or a queued job running outside the HTTP context (so with no tenant resolved by the middleware) can all expose one tenant's data to another. This is, historically, the source of most publicly documented multi-tenant security incidents (CVEs and bug bounty reports against SaaS products).

Diagnosing leaks in a column-based implementation

If this third strategy is already in place, the priority audit is listing every access to tenant-scoped tables that does not go through the global scope:

# Find raw queries that potentially bypass the scope
grep -rn "DB::table(" app/ --include="*.php" | grep -v "tenant_id"

# Find jobs that touch tenant-scoped models
grep -rln "implements ShouldQueue" app/Jobs/

Every job found by the second command needs manual review: if it touches a model with TenantScope, the tenant must be explicitly serialized into the job and reapplied at execution time, never assumed to be available through an HTTP request context that no longer exists once the job runs in the queue.

class GenerateInvoicePdf implements ShouldQueue
{
    public function __construct(private int $tenantId, private int $invoiceId) {}

    public function handle(): void
    {
        app()->instance('currentTenant', Tenant::find($this->tenantId));
        // The global scope now applies correctly
        $invoice = Invoice::findOrFail($this->invoiceId);
        // ...
    }
}

The tradeoffs, named explicitly

| Criterion | Database per tenant | Schema per tenant | Shared tenant_id | |---|---|---|---| | Isolation strength | Maximum (DB engine) | Strong (DB engine, PostgreSQL) | Depends on application code | | Operational cost | High (N databases to back up/monitor) | Moderate | Low | | Cross-tenant reporting | Complex (multi-database aggregation) | Moderate | Simple | | Database portability | Yes | No (PostgreSQL-specific) | Yes | | Scalability with tenant count | Limited (connection pools) | Good up to several hundred | Excellent |

There is no absolute "best" option: a SaaS sold to large accounts with strict compliance requirements (healthcare, regulated finance) often justifies the operational cost of a database per tenant for the isolation guarantee it brings to the contract. A B2B SaaS with high volumes of small accounts (thousands of tenants) rarely tolerates a database per tenant and naturally gravitates to the shared column, backed by strict code discipline to compensate.

When the shared column becomes risky

If the product handles regulated data (healthcare, banking) or a customer contractually requires demonstrable physical isolation under audit, the tenant_id column alone usually is not enough, no matter how good the code is: an external security auditor will ask for infrastructure-level proof of isolation, not an application-level guarantee. In that case, schema-per-tenant (or database-per-tenant for the strictest requirements) is not one option among several, it is a constraint imposed by the regulatory context.

A hybrid worth considering: shared column with a dedicated read replica

A pattern that does not show up often enough in this discussion: the shared tenant_id column does not have to mean a single, undifferentiated database for every workload. For reporting and analytics queries that scan across all tenants (usage dashboards, billing aggregation), routing those reads to a dedicated replica keeps heavy cross-tenant scans from competing with the latency-sensitive queries that serve live tenant traffic.

// config/database.php
'connections' => [
    'mysql' => [
        // primary connection, used for all tenant-scoped writes and reads
    ],
    'mysql_reporting' => [
        // read replica, used only for cross-tenant aggregation
        'read' => [
            'host' => [env('DB_REPORTING_HOST')],
        ],
        'sticky' => false,
    ],
],
class TenantUsageReport
{
    public function generate(): Collection
    {
        return DB::connection('mysql_reporting')
            ->table('invoices')
            ->selectRaw('tenant_id, SUM(amount) as total')
            ->groupBy('tenant_id')
            ->get();
    }
}

This does not change the isolation model (the global scope still governs tenant-scoped application traffic); it is an operational refinement that keeps a reporting job from degrading response times for every tenant at once, a failure mode that is easy to overlook until a dashboard query locks a row that a customer-facing request also needs.

Testing isolation, not just trusting it

Whichever strategy is chosen, the isolation guarantee should be backed by an automated test that actively tries to break it, not just code review vigilance.

public function test_user_cannot_access_another_tenants_invoice(): void
{
    $tenantA = Tenant::factory()->create();
    $tenantB = Tenant::factory()->create();

    $invoice = Invoice::factory()->for($tenantB)->create();

    $this->actingAsTenant($tenantA)
        ->get("/invoices/{$invoice->id}")
        ->assertNotFound(); // never assertForbidden: existence itself should not leak
}

Asserting 404 rather than 403 matters here: a 403 confirms the resource exists under a different tenant, which is itself a small information leak in a strict multi-tenant context. This single test, run on every pipeline, catches the single most common regression in a shared-column setup: a new endpoint or job added without the tenant filter applied.

Takeaway

Choosing between database, schema and shared column is not a matter of technical preference but of what the customer contract and applicable regulation require as proof of isolation. The shared column with a global scope is the cheapest default, provided raw queries and queued jobs that can bypass it are audited systematically rather than assumed safe.