Search code examples
laravellaravel-5cookiesremember-me

How to change the "remember-me" Laravel cookie lifetime?


I use the built-in "Remember me" functionnality of Laravel 5.8. I checked the cookies and saw the remember-me cookie expires in about 5 years. That is way to long and I would like to shorten it. As Laravel automaticly creates the cookie, I don't have the hand on it. How can I do this ?


Solution

  • The remember me duration can be overridden by overriding the AuthenticatesUsers trait. You could add the following code to LoginController that overrides the trait in the following controller:

    protected function sendLoginResponse(Request $request)
    {
        $customRememberMeTimeInMinutes = 10;
        $rememberTokenCookieKey = Auth::getRecallerName();
        Cookie::queue($rememberTokenCookieKey, Cookie::get($rememberTokenCookieKey), $customRememberMeTimeInMinutes);
    
        $request->session()->regenerate();
    
        $this->clearLoginAttempts($request);
    
        return $this->authenticated($request, $this->guard()->user())
                ?: redirect()->intended($this->redirectPath());
    }
    
    

    An alternative is to invalidate the remember me session by setting the remember_token in the users table to an empty value. Example:

    $user = Auth::user();
    $user->remember_token = null;
    $user->save();