Add cookie option on Initialize Tenancy by Request identification
Description
Add Tenant Identification by Request Cookie Identification on InitializeTenancyByRequestData middleware payload which can work the same as Request Header Identification.
Why this should be added
When using InitializeTenancyByRequestData
In a SPA front-end we need to set a header on every request that will be send to our backend or set query params with tenant id.
So in this approach When a user login will receive X-Tenant cookie with value tenant id from Authentication Controller which will be use on the next requests to identify tenant.
I tested it on my project and it works:
How it works
on Authentication controller
$response->withCookie(cookie('X-Tenant', $tenant, 120));
in InitializeTenancyByRequestData middleware from stancl\tenancy\src\Middleware\InitializeTenancyByRequestData.php
we add another condition to check if request cookie exist with key X-Tenant then we use the value
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);
}
// add below condition ...........
elseif (static::$header && $request->hasCookie(static::$header)) { // check if request has cookie with key X-Tenant
$tenant = $request->cookie(static::$header);
}
return $tenant;
}
``