Laravel登录:如何校验用户状态并处理Auth::attempt异常?
Solution for Laravel Login: Differentiate Inactive User vs Wrong Password
The problem with your current code is that adding 'active' => 1 to the credentials array makes Auth::attempt() fail for both inactive users and incorrect passwords—with no way to distinguish between the two scenarios. Here's a straightforward fix by splitting the checks into explicit steps:
Step-by-Step Breakdown
Instead of bundling the active status check into the login credentials, we'll:
- First fetch the user by their email to confirm they exist.
- Check if the user is inactive before verifying their password.
- Only attempt to log them in if they're an active user with the correct password.
Full Code Implementation
use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; use App\Models\User; // Ensure your User model is imported public function handleLogin(Request $request) { // Optional but recommended: Validate input first $request->validate([ 'email' => 'required|email', 'password' => 'required', ]); $email = $request->input('email'); $password = $request->input('password'); // Find the user using their email address $user = User::where('email', $email)->first(); // Case 1: No user exists with this email if (!$user) { return back()->withErrors([ 'email' => '无效的邮箱或密码', // Generic message to avoid exposing user existence ]); } // Case 2: User exists but is inactive if (!$user->active) { return back()->withErrors([ 'email' => '此用户处于非活跃状态,请联系管理员', ]); } // Case 3: User is active, verify password and log in if (Auth::attempt(['email' => $email, 'password' => $password], $request->has('remember'))) { // Login successful, redirect to the intended page return redirect()->intended('/dashboard'); } else { // Password is incorrect return back()->withErrors([ 'password' => '无效的邮箱或密码', ]); } }
Key Details
- Security Note: Revealing that an email is registered (via the inactive message) could be a minor security risk. If you want to avoid this, you could return a generic message for both non-existent users and inactive accounts, but this aligns with your original requirement for specific feedback.
- Laravel Best Practices: Using
Requestinstead ofInput::get()is preferred in modern Laravel versions. Input validation ensures you're working with properly formatted values before proceeding. - Remember Me Functionality: The
$request->has('remember')checks if the user ticked the "remember me" checkbox, passing that preference to the login attempt.
内容的提问来源于stack exchange,提问作者Saurav
相关产品推荐
相关产品推荐

