Back to All Nuggets
Laravel php ⏱️ 2 min read
Production Implementation
Ask endoAI
<?php

declare(strict_types=1);

namespace App\Http\Middleware;

use App\Models\Tenant;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\DB;
use Symfony\Component\HttpFoundation\Response;

class ResolveTenantConnectionMiddleware
{
    public function handle(Request $request, Closure $next): Response
    {
        $tenantId = $request->header('X-Tenant-ID') ?? explode('.', $request->getHost())[0];
        $tenant = Tenant::where('domain', $tenantId)->orWhere('id', $tenantId)->first();
        if (!$tenant || !$tenant->is_active) {
            return response()->json(['error' => 'Tenant not found.'], 404);
        }
        Config::set('database.connections.tenant.database', $tenant->database_name);
        DB::purge('tenant');
        DB::reconnect('tenant');
        DB::setDefaultConnection('tenant');
        app()->instance('currentTenant', $tenant);
        return $next($request);
    }
}

Enterprise multi-tenancy and high-throughput architectural patterns require dedicated database partitioning, connection pooling, and resilient worker strategies...

By subscribing to our developer tier, you unlock complete production source code, downloadable PowerPoint decks, and interactive labs.

Premium Developer Content

Join our membership for KES 500/month to unlock all comprehensive engineering deep-dives and slide decks.

Unlock Full Access (KES 500)

Accelerate Your Engineering Career

Get monthly masterclasses, exclusive code snippets, and direct architectural reviews.

Become a Supporter • KES 500 / Month