Laravel修改LoginController:让用户自主选择登录是否记住我
Hey there! Let's get this sorted out for you step by step, since you're working with Laravel 7 and the laravel/ui package.
Step 1: Make sure your login view has the "Remember Me" checkbox
First, head over to your login view file at resources/views/auth/login.blade.php. You need to add (or verify) a checkbox with the name remember — this is what Laravel looks for to determine if the user wants to be remembered.
Here's what that section should look like:
<div class="form-check"> <input class="form-check-input" type="checkbox" name="remember" id="remember"> <label class="form-check-label" for="remember"> Remember Me </label> </div>
If this checkbox is already there, great! Move on to the next step.
Step 2: Check (and adjust if needed) the attemptLogin method in your LoginController
The LoginController uses the AuthenticatesUsers trait by default, which handles the "remember me" logic out of the box. But if you or someone else modified the attemptLogin method, it might be forcing "remember me" for all users.
Open up app/Http/Controllers/Auth/LoginController.php and look for the attemptLogin method. If it looks like this (forcing true for the remember parameter):
protected function attemptLogin(Request $request) { return $this->guard()->attempt( $this->credentials($request), true ); }
You need to change it to check if the remember checkbox was submitted:
protected function attemptLogin(Request $request) { return $this->guard()->attempt( $this->credentials($request), $request->filled('remember') ); }
If you don't have an attemptLogin method in your LoginController at all, that's totally fine! The default trait method already does exactly this — it checks if the remember field exists in the request (which happens when the checkbox is checked) and enables the remember functionality only then.
How this works under the hood
The attempt method on the guard takes two parameters:
- The user credentials (email/password)
- A boolean flag for whether to "remember" the user
$request->filled('remember') returns true only if the checkbox was checked (since unchecked checkboxes don't get sent with the request), so this will only enable the remember me feature when the user explicitly checks the box.
That's all! Now your users can choose whether they want to stay logged in or not.
内容的提问来源于stack exchange,提问作者BloodWork01

