52 lines
1.8 KiB
PHP
52 lines
1.8 KiB
PHP
<?php
|
|
|
|
namespace App\Http\Middleware;
|
|
|
|
use Closure;
|
|
use Illuminate\Http\Request;
|
|
use Stancl\Tenancy\Middleware\InitializeTenancyByDomain;
|
|
|
|
class IdentifyTenantIfNeeded
|
|
{
|
|
/**
|
|
* Handle an incoming request.
|
|
*/
|
|
public function handle(Request $request, Closure $next)
|
|
{
|
|
$host = $request->getHost();
|
|
$centralDomains = config('tenancy.central_domains', ['127.0.0.1', 'localhost', 'hrm.test']);
|
|
|
|
if (in_array($host, $centralDomains, true) || filter_var($host, FILTER_VALIDATE_IP)) {
|
|
if (class_exists(\Spatie\Permission\PermissionRegistrar::class)) {
|
|
app(\Spatie\Permission\PermissionRegistrar::class)->forgetCachedPermissions();
|
|
}
|
|
return $next($request);
|
|
}
|
|
|
|
try {
|
|
return app(InitializeTenancyByDomain::class)->handle($request, $next);
|
|
} catch (\Stancl\Tenancy\Exceptions\TenantDatabaseDoesNotExistException $e) {
|
|
$tenant = tenant();
|
|
if ($tenant) {
|
|
$tenantId = $tenant->id;
|
|
$dbFile = database_path('tenant_' . $tenantId);
|
|
$dbFileSqlite = database_path('tenant_' . $tenantId . '.sqlite');
|
|
if (!file_exists($dbFile)) { touch($dbFile); }
|
|
if (!file_exists($dbFileSqlite)) { touch($dbFileSqlite); }
|
|
|
|
\Illuminate\Support\Facades\Artisan::call('migrate', [
|
|
'--database' => 'tenant',
|
|
'--path' => [
|
|
'database/migrations/tenant',
|
|
'database/migrations',
|
|
],
|
|
'--force' => true,
|
|
]);
|
|
|
|
return app(InitializeTenancyByDomain::class)->handle($request, $next);
|
|
}
|
|
abort(503, 'Tenant database setup is incomplete.');
|
|
}
|
|
}
|
|
}
|