Laravel 8:在中间件中设置会话生存期



我发现了一些关于如何在中间件中动态设置会话生存期的说明。我创建了一个中间件;session.lifetime";取决于路由名称,并将其放在我所有中间件的顶部,以便在调用StartSession之前先调用它。但无论我尝试什么,Laravel总是采用env文件中定义的默认会话生存期。

你知道可能是什么问题吗?Laravel 8(或7(有什么变化吗?我发现的必备品是Laravel 5,我无法找到更多关于它的最新信息。

我的中间件就是这样的:

/**
* 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);
}

坦克需要你的帮助!

看看这里:https://laravel.com/docs/8.x/configuration

Laravel 8正在使用这样的配置助手:

//To set configuration values at runtime, pass an array to the config helper:
config(['app.timezone' => 'America/Chicago']);

有点像这样?

if ($lifetimeMin !== null) {
config(['session.lifetime' => $lifetimeMin]);
} elseif (str_starts_with($request->route()->getName(), 'api.')) {
$apiLifetime = config('session.lifetime_api', 525600);
config(['session.lifetime' => $apiLifetime]);
} elseif (str_starts_with($request->route()->getName(), 'admin.')) {
$adminLifetime = config('session.lifetime_admin', 120);
config(['session.lifetime' => $adminLifetime]);
}

此外。。默认配置从env文件中检索值。我可以想象旧的Config::set再也不能重载这个了。您是否尝试过在不使用env((方法的情况下设置配置?

'lifetime' => env('SESSION_LIFETIME', 120),

有点像

'lifetime' => 120,

最新更新