I found couple of instructions how to set the session lifetime dynamically in a middleware. I created a middleware which set the config "session.lifetime" depending on the route name and put it on the top of all my middlewares so it will be called first before StartSession gets called. But no matter what I try, Laravel always takes the default session lifetime defined in the env file.
Any idea what the problem could be? Did something change in Laravel 8 (or 7)? Must stuff I found was for Laravel 5 and I wasn't been able to find more current information about it..
That's how my middleware looks like:
/**
* Set the session lifetime for the current request.
*
* @param Request $request current request
* @param Closure $next next handler
* @param int|null $lifetimeMin lifetime in minutes.
*
* @return mixed
*/
public function handle(Request $request, Closure $next, ?int $lifetimeMin = null)
{
if ($lifetimeMin !== null) {
Config::set('session.lifetime', $lifetimeMin);
} elseif (str_starts_with($request->route()->getName(), 'api.')) {
$apiLifetime = Config::get('session.lifetime_api', 525600);
Config::set('session.lifetime', $apiLifetime);
} elseif (str_starts_with($request->route()->getName(), 'admin.')) {
$adminLifetime = Config::get('session.lifetime_admin', 120);
Config::set('session.lifetime', $adminLifetime);
}
return $next($request);
}
Tanks for your help!