43 lines
1.1 KiB
PHP
43 lines
1.1 KiB
PHP
<?php
|
|
|
|
namespace App\Http\Middleware;
|
|
|
|
use App\Models\BusinessDomain;
|
|
use App\Services\Tenant\TenantContext;
|
|
use App\Services\Tenant\DomainNormalizer;
|
|
use Closure;
|
|
use Illuminate\Http\Request;
|
|
use Symfony\Component\HttpFoundation\Response;
|
|
use Throwable;
|
|
|
|
class ResolveTenant
|
|
{
|
|
public function handle(Request $request, Closure $next): Response
|
|
{
|
|
$hostname = null;
|
|
try {
|
|
$hostname = app(DomainNormalizer::class)->normalize($request->getHost());
|
|
$business = BusinessDomain::query()
|
|
->where('hostname', $hostname)
|
|
->where('isActive', true)
|
|
->with('business')
|
|
->first()?->business;
|
|
|
|
} catch (Throwable) {
|
|
// The install page and framework smoke tests must remain
|
|
// reachable before the tenant schema has been created.
|
|
$business = null;
|
|
}
|
|
|
|
if (! $business) {
|
|
app(TenantContext::class)->forget();
|
|
}
|
|
|
|
if ($business) {
|
|
app(TenantContext::class)->set($business);
|
|
}
|
|
|
|
return $next($request);
|
|
}
|
|
}
|