简体   繁体   English

如何在 Laravel 8 中实现记住我?

[英]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.我正在使用在 Laravel 中构建的 LoginController。

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: 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!任何帮助将不胜感激!

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.');
    }
}

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!看起来您正在使用 Laravel 提供的默认身份验证,这意味着如果您在views/auth/login.blade.php中具有默认表单输入名称值,则无需在Http/Controllers/Auth/LoginController中执行任何操作即可记住用户。 views/auth/login.blade.php表格,看起来像你做的!

The only thing you need to ensure is that in your users table you store a remember_token field.您唯一需要确保的是在您的users表中存储了一个remember_token字段。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM