Trueno
Trueno

Reputation: 21

How to implement Remember me in Laravel 8?

I have a login form and a remember me checkbox. I want the username and the password to be automatically filled in if the user checked the remember me checkbox on the previous login, but it is not working for now. I'm using the LoginController that was built in Laravel.

LoginController:

<?php


namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use Illuminate\Validation\ValidationException;

class LoginController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */
    use AuthenticatesUsers;

    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo = RouteServiceProvider::DASHBOARD;

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest')->except('logout');
    }

    /**
     * Check either username or email.
     * @return string
     */
    public function username()
    {
        $identity  = request()->get('identity');
        $fieldName = filter_var($identity, FILTER_VALIDATE_EMAIL) ? 'email' : 'name';
        request()->merge([$fieldName => $identity]);
        return $fieldName;
    }

     /**
     * Validate the user login.
     * @param Request $request
     */
    protected function validateLogin(Request $request)
    {
        $this->validate(
            $request,
            [
                'identity' => 'required|string',
                'password' => 'required|string',
            ],
            [
                'identity.required' => 'Username or email is required',
                'password.required' => 'Password is required',
            ]
        );
    }
    /**
     * @param Request $request
     * @throws ValidationException
     */
    protected function sendFailedLoginResponse(Request $request)
    {
        $request->session()->put('login_error', trans('auth.failed'));
        throw ValidationException::withMessages(
            [
                'error' => [trans('auth.failed')],
            ]
        );
    }
}

login.blade.php:

@extends('layouts.app')

@section('content')
<div class="topMargin container">
  <br><br>
  <div class="row justify-content-center">
      <div class="col-md-8">
          <div class="card">
              <div class="card-header" text-align="center">{{ __('Login') }}</div>

              <div class="card-body">
                  <form method="POST" action="{{ route('login') }}">
                      @csrf

                      <div class="form-group row">
                          {{-- <label for="email" class="col-sm-4 col-form-label text-md-right">{{ __('E-Mail Address') }}</label> --}}

                          <div class="col-md-12">
                              <input id="identity" type="identity" class="form-control{{ $errors->has('identity') ? ' is-invalid' : '' }}" name="identity" value="{{ old('identity') }}" placeholder="{{ __('Email or Username') }}" required autofocus>

                              @if ($errors->has('identity'))
                                  <span class="invalid-feedback">
                                      <strong>{{ $errors->first('identity') }}</strong>
                                  </span>
                              @endif
                          </div>
                      </div>

                      <div class="form-group row">
                          {{-- <label for="password" class="col-md-4 col-form-label text-md-right">{{ __('Password') }}</label> --}}

                          <div class="col-md-12">
                              <input id="password" type="password" class="form-control{{ $errors->has('password') ? ' is-invalid' : '' }}" name="password" placeholder="Password" required>

                              @if ($errors->has('password'))
                                  <span class="invalid-feedback">
                                      <strong>{{ $errors->first('password') }}</strong>
                                  </span>
                              @endif
                          </div>
                      </div>

                      <div class="form-group">
                          <div style="text-align:center">
                              <div class="checkbox">
                                  <label>
                                      <input type="checkbox" name="remember" {{ old('remember') ? 'checked' : '' }}> {{ __('Remember Me') }}
                                  </label>
                              </div>
                          </div>
                      </div>

                      <div class="form-group">
                          <div style="text-align:center">
                              <button type="submit" class="btn btn-primary">
                                  {{ __('Login') }}
                              </button>
                          </div>
                          <br>
                          <div style="text-align:center">
                              <a class="btn btn-link" href="{{ route('password.request') }}">
                                  {{ __('Forgot Your Password?') }}
                              </a>
                          </div>
                      </div>
                  </form>
              </div>
          </div>
      </div>
  </div>
</div>
@endsection

Any help would be greatly appreciated!

Upvotes: 2

Views: 18488

Answers (2)

Nick Howarth
Nick Howarth

Reputation: 634

Looks like you are using the default Authentication provided by Laravel, meaning you do not need to do anything in your Http/Controllers/Auth/LoginController to remember the user if you have the default form input name values in the views/auth/login.blade.php form, which it looks like you do!

The only thing you need to ensure is that in your users table you store a remember_token field.

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

Upvotes: 2

kusma
kusma

Reputation: 69

public function webLoginPost(Request $request)
{
    $this->validate($request, [
        'email' => 'required|email',
        'password' => 'required',
    ]);


    $remember_me = $request->has('remember_me') ? true : false; 


    if (auth()->attempt(['email' => $request->input('email'), 'password' => $request->input('password')], $remember_me))
    {
        $user = auth()->user();
        dd($user);
    }else{
        return back()->with('error','your username and password are wrong.');
    }
}

Upvotes: 1

Related Questions