Laravel: “Remember me” active by default
If you’re looking to have the “Remember me” functionality active by default in the login and registration process, in Laravel, this is handled through the AuthenticatesUsers and RegistersUsers traits which are used in the LoginController and RegisterController.
LoginController
In the AuthenticatesUsers
trait, the method that actually attempts the login and where the “remember me” parameter is considered is attemptLogin()
. This is the original code:
protected function attemptLogin(Request $request)
{
return $this->guard()->attempt(
$this->credentials($request), $request->boolean('remember')
);
}
Here, $request->boolean('remember')
is where Laravel checks if the “remember me” checkbox has been checked on the login form. It converts the ‘remember’ request value to boolean, which is then passed as the second argument to attempt()
to handle the “remember me” functionality.
To override this behavior:
If you want to ensure “remember me” is always true
, regardless of whether the user has checked the box or not, you should override this method in your LoginController
. Specifically:
- Copy the entire
attemptLogin()
method from theAuthenticatesUsers
trait. - Paste it into your
LoginController
. - Replace
$request->boolean('remember')
withtrue
.
Here is how you would modify attemptLogin()
in your LoginController
:
protected function attemptLogin(Request $request)
{
return $this->guard()->attempt(
$this->credentials($request), true // always remember the user
);
}
With this change, the “remember me” functionality will always be activated whenever a user logs in, whether they check the box or not.
RegisterController
- Override the
registered
method: This step ensures that after the user registers, they are logged in with “remember me” set totrue
.
protected function registered(Request $request, $user)
{
Auth::guard()->login($user, true);
return redirect($this->redirectPath());
}