Home > Mobile >  How to change duration of "remember me" cookie in laravel 9?
How to change duration of "remember me" cookie in laravel 9?

Time:08-24

I'm using laravel 9 and implementing login authentication manually without the laravel starter kit, I've read a lot of questions like this but most of the answers only apply to those using the starter kit, I've also read some of the other answers without the starter kit but most of them don't work.

This is my login method in the controller:

public function auth()
{
    // validation
    request()->validate([
        'emailOrUsername' => ['required'],
        'password' => ['required']
    ]);

    // Check if the user clicks "remember me" in the login form
    $remember = (request()->remember) ? true : false;

    // If login using email
    if (Auth::attempt(['email' => request()->emailOrUsername, 'password' => request()->password], $remember)) {
        request()->session()->regenerate();
        return redirect()->intended('/dashboard');
    }
    // If login using username
    else if (Auth::attempt(['username' => request()->emailOrUsername, 'password' => request()->password], $remember)) {
        request()->session()->regenerate();
        return redirect()->intended('/dashboard');
    } 
    // If incorrect credentials
    else {
        return back()->with('errorAlert', 'Maaf, email/username atau password yang anda masukkan salah');
    }
}

I also noticed that it seems the default cookie duration for "remember me" is set in the Illuminate\Auth\SessionGuard namespace (but I didn't find the explanation in the official laravel documentation), I see that class has a setRememberDuration() method to change the duration of the "remember me" cookie, but I don't know how to properly call it, I've used Auth::setRememberDuration(1000) but it doesn't work. Is there any other way to set the "remember me" cookie duration using that method? Or is there another way to change the duration without using that method?

CodePudding user response:

You can set it in config/auth.php :

'guards' => [
    'web'     => [
        'driver'   => 'session',
        'provider' => 'users',
        'remember' => now()->addDays(7)->diffInMinutes(),
    ]
],

it's then used by the AuthManager :

if (isset($config['remember'])) {
    $guard->setRememberDuration($config['remember']);
}

edit:

For future readers, this answers only work from Laravel 8.65.0

  • Related