Search code examples
laravellaravel-authentication

"Remember me" doesn't work, remember token always empty


The "remember me" doesn't work. Even if checked before login, the field "remember_token" is always empty in the database and it doesn't remember users at all.

Here is my login method in the LoginController file

public function login(Request $request)
    {
        $this->validateLogin($request);

        // If the class is using the ThrottlesLogins trait, we can automatically throttle
        // the login attempts for this application. We'll key this by the username and
        // the IP address of the client making these requests into this application.
        if ($this->hasTooManyLoginAttempts($request)) {
            $this->fireLockoutEvent($request);

            return $this->sendLockoutResponse($request);
        }

        if ($this->attemptLogin($request)) {
            return $this->sendLoginResponse($request);
        }

        // If the login attempt was unsuccessful we will increment the number of attempts
        // to login and redirect the user back to the login form. Of course, when this
        // user surpasses their maximum number of attempts they will get locked out.
        $this->incrementLoginAttempts($request);

        return $this->sendFailedLoginResponse($request);
    }

I tried putting the remember me field as a second parameter to the attemptLogin method, but no change


Solution

  • Laravel authentication offers remember me functionality out of the box.

    In order to use it you need to do 2 things:

    1- add remember_token column in your users table - this is where the token will be stored

    2- pass true as a second parameter of Auth::attempt() to enable remember me behaviour If you do this, Laravel will generate a token that will be saved in users table and in a cookie. On subsequent requests, even if session cookie is not available, user will be authenticated automatically as long as remember-me cookie is there.

    You can find more details and example in the docs:

    https://laravel.com/docs/8.x/authentication#remembering-users
    

    this piece of code may help you, i cutted this from laravel sample project:

    if ( Auth::attempt($this->only('email', 'password'), $this->filled('remember')) ){
        // logged in succcessfully, if remember key exist in request then remember me will be true
    }