Laravel 8: set session lifetime in middleware

2.6k views Asked by At

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!

1

There are 1 answers

0
Erik Hoekstra On

Take a look here: https://laravel.com/docs/8.x/configuration

Laravel 8 is using a config helper like so:

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

Somewhat like this?

  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]);
  }

Also .. the default config retrieves values from the env file. I can imagine the older Config::set can't overload this any longer. Have you tried to set the config without the env() method?

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

To somewhat like so

'lifetime' => 120,