QA
Senior LevelLaravel

How do you architect Single-Database vs Multi-Database Multi-Tenancy in Laravel?

❓ Interview Prompt: Compare Single-Database tenant_id Global Scopes vs Multi-Database connection switching, dynamic DB connections, and tenant resolution middleware.

Multi-Tenant applications isolate data across distinct customer accounts (tenants):

1. Single-Database (Row-Level Isolation):

All tenants share one database. Enforces isolation using a 'tenant_id' column combined with a Global Scope on all Eloquent models.

2. Multi-Database (Isolated DB per Tenant):

Each tenant gets an isolated database. Middleware resolves the tenant from domain/headers and dynamically sets the default DB connection: 'DB::purge("tenant"); config(["database.connections.tenant.database" => $tenantDb]);'.

Code Implementation Example

php
<?php
namespace AppHttpMiddleware;

use Closure;
use IlluminateSupportFacadesDB;
use AppModelsTenant;

class SwitchTenantDatabase
{
    public function handle($request, Closure $next) {
        $tenant = Tenant::where('domain', $request->getHost())->firstOrFail();
        config(['database.connections.tenant.database' => $tenant->db_name]);
        DB::purge('tenant');
        DB::reconnect('tenant');
        return $next($request);
    }
}
💡Dynamic multi-tenant database connection switching middleware.
🎯 Interview Key Takeaway

Use row-level tenant_id global scopes for single-database multi-tenancy, or dynamic connection switching for isolated databases.

#Multi-Tenancy#Architecture#Database Isolation#Senior
Back to all Laravel Questions→

More Laravel Interview Questions

Beginner LevelLaravel

How does the Laravel Service Container manage Dependency Injection and Bindings?

Beginner LevelLaravel

How does Routing work in Laravel including Named Routes and Route Parameters?

Beginner LevelLaravel

What is Blade Templating and how do custom directives work?