Laravel多用户类型登录验证逻辑:按指定类型优先级实现登录
Hey there! Let's walk through how to implement your desired login validation logic step by step. The key thing to note here is that Laravel's Auth::attempt() method uses exact field matching—so you can't directly pass an array like 'type' => [1,2] to check both user types at once. Instead, we'll split the validation into two sequential checks to prioritize type 1 users first.
Step-by-Step Implementation
1. First Validate Type 1 Users
We'll start by constructing credentials specifically for active type 1 users and attempt to authenticate with those. If this succeeds, we'll proceed with the login flow immediately.
2. Fallback to Type 2 Users
If the first authentication attempt fails (either no matching type 1 user exists or credentials are wrong), we'll then construct credentials for active type 2 users and try again.
3. Handle Authentication Failure
If both attempts fail, we'll return an error message to the user.
Complete Code Example
Here's how this looks in practice (you'd typically add this to your LoginController or a dedicated auth service):
use Illuminate\Support\Facades\Auth; use Illuminate\Http\Request; public function login(Request $request) { // Retrieve credentials from the request $username = $request->input('email'); $password = $request->input('password'); // First attempt: authenticate active type 1 users $credentialsType1 = [ 'email' => $username, 'password' => $password, 'active' => 1, 'type' => 1 ]; if (Auth::attempt($credentialsType1, true)) { // Type 1 user authenticated successfully return redirect()->intended('/dashboard'); // Redirect to your desired page } // Second attempt: fallback to active type 2 users $credentialsType2 = [ 'email' => $username, 'password' => $password, 'active' => 1, 'type' => 2 ]; if (Auth::attempt($credentialsType2, true)) { // Type 2 user authenticated successfully return redirect()->intended('/dashboard'); } // Both attempts failed: return error message return back()->withErrors([ 'email' => 'No matching active user found with the provided credentials.', ]); }
Key Details to Keep in Mind
- The second parameter
trueinAuth::attempt()enables the "remember me" functionality. If you don't need this, replace it withfalseor omit it entirely. - Ensure your
Usermodel has the necessary fields (email,password,active,type) and that they're accessible for querying (check your$fillableor$guardedproperties). - This logic strictly follows your priority rule: type 1 users are checked first, and type 2 users only get evaluated if the first attempt fails.
内容的提问来源于stack exchange,提问作者Saurav

