diff --git a/src/Middleware/InitializeTenancyByRequestData.php b/src/Middleware/InitializeTenancyByRequestData.php index ba587d9a..ca29f3d7 100644 --- a/src/Middleware/InitializeTenancyByRequestData.php +++ b/src/Middleware/InitializeTenancyByRequestData.php @@ -12,6 +12,7 @@ use Stancl\Tenancy\Tenancy; class InitializeTenancyByRequestData extends IdentificationMiddleware { public static string $header = 'X-Tenant'; + public static string $cookie = 'X-Tenant'; public static string $queryParameter = 'tenant'; public static ?Closure $onFail = null; @@ -33,13 +34,18 @@ class InitializeTenancyByRequestData extends IdentificationMiddleware protected function getPayload(Request $request): ?string { - $tenant = null; if (static::$header && $request->hasHeader(static::$header)) { - $tenant = $request->header(static::$header); - } elseif (static::$queryParameter && $request->has(static::$queryParameter)) { - $tenant = $request->get(static::$queryParameter); + return $request->header(static::$header); } - return $tenant; + if (static::$queryParameter && $request->has(static::$queryParameter)) { + return $request->get(static::$queryParameter); + } + + if (static::$cookie && $request->hasCookie(static::$cookie)) { + return $request->cookie(static::$cookie); + } + + return null; } } diff --git a/tests/RequestDataIdentificationTest.php b/tests/RequestDataIdentificationTest.php index e5a05f65..e10c00e1 100644 --- a/tests/RequestDataIdentificationTest.php +++ b/tests/RequestDataIdentificationTest.php @@ -20,19 +20,18 @@ beforeEach(function () { afterEach(function () { InitializeTenancyByRequestData::$header = 'X-Tenant'; + InitializeTenancyByRequestData::$cookie = 'X-Tenant'; InitializeTenancyByRequestData::$queryParameter = 'tenant'; }); test('header identification works', function () { InitializeTenancyByRequestData::$header = 'X-Tenant'; $tenant = Tenant::create(); - $tenant2 = Tenant::create(); $this ->withoutExceptionHandling() - ->get('test', [ - 'X-Tenant' => $tenant->id, - ]) + ->withHeader('X-Tenant', $tenant->id) + ->get('test') ->assertSee($tenant->id); }); @@ -40,10 +39,20 @@ test('query parameter identification works', function () { InitializeTenancyByRequestData::$queryParameter = 'tenant'; $tenant = Tenant::create(); - $tenant2 = Tenant::create(); $this ->withoutExceptionHandling() ->get('test?tenant=' . $tenant->id) ->assertSee($tenant->id); }); + +test('cookie identification works', function () { + InitializeTenancyByRequestData::$cookie = 'X-Tenant'; + $tenant = Tenant::create(); + + $this + ->withoutExceptionHandling() + ->withUnencryptedCookie('X-Tenant', $tenant->id) + ->get('test',) + ->assertSee($tenant->id); +});