62 lines
1.4 KiB
PHP
62 lines
1.4 KiB
PHP
<?php
|
|
|
|
namespace App\Http\Middleware;
|
|
|
|
use Closure;
|
|
use Illuminate\Http\Request;
|
|
use Symfony\Component\HttpFoundation\Response;
|
|
|
|
class TenantScope
|
|
{
|
|
/**
|
|
* Handle an incoming request.
|
|
* Set the global tenant_id so that queries are scoped to the current tenant.
|
|
*/
|
|
public function handle(Request $request, Closure $next): Response
|
|
{
|
|
$tenantId = session('tenant_id');
|
|
|
|
if ($tenantId) {
|
|
// Set the global tenant context for scoped queries
|
|
app()->instance('tenant_id', $tenantId);
|
|
}
|
|
|
|
return $next($request);
|
|
}
|
|
|
|
/**
|
|
* Run a callback without the tenant scope.
|
|
* Useful for super-admin operations that span all tenants.
|
|
*/
|
|
public static function withoutTenantScope(callable $callback): mixed
|
|
{
|
|
$previousTenantId = app('tenant_id');
|
|
|
|
// Clear the tenant context
|
|
app()->instance('tenant_id', null);
|
|
|
|
try {
|
|
return $callback();
|
|
} finally {
|
|
// Restore the previous tenant context
|
|
app()->instance('tenant_id', $previousTenantId);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Get the current tenant ID.
|
|
*/
|
|
public static function getCurrentTenantId(): ?int
|
|
{
|
|
return app('tenant_id');
|
|
}
|
|
|
|
/**
|
|
* Check if a tenant scope is currently active.
|
|
*/
|
|
public static function hasTenantScope(): bool
|
|
{
|
|
return app('tenant_id') !== null;
|
|
}
|
|
}
|