'Laravel sanctum getting the right user

I'm trying to build an API with Laravel and Sanctum for an existing system with a database that I cannot modify, and I'm having problems with authentication.

The system has a not very common user table, where a user can have the same id but with 3 different 'types'. So, at login, I send the email, password, and the type. It's not a problem and successfully logs in.

But when trying to recover the logged-in user, it shows the wrong user. Example:

Login:
(this user has id 8)
email: [email protected]
password: xxxxx
type: 2
Recovered user:
(this user also has id 8)
email: [email protected]
passsword: xxxxx
type: 1

I think it's because they have the same ID and Laravel takes the first user, which is not necessarily correct.

I'm stuck with this... What should I do? Is there a way to get the right user? Thanks

Login function

public function login(Request $request)
{
    $validator = Validator::make($request->all(), [
        'email' => 'required|email',
        'password' => 'required',
        'tip_id' => 'required|int'
    ]);

    if (!Auth::attempt($validator->validated())) {
        return response()->json(['error' => 'Email e/ou senha incorretos'], 400);
    } else {
        $user = User::where('email', $request->input('email'))->where('tip_id', $request->input('tip_id'))->first();

        $item = time().rand(0, 9999);
        $token = $user->createToken($item)->plainTextToken;

        return response()->json(['token' => $token]);
    }
}

User profile function

public function profile()
{
    return response()->json(['user' => auth()->user()]);
}


Solution 1:[1]

I know you must have resolved this, but I would like to share my way of achieving this so that someone other can get help.

I will create separate table in new database to manage sanctum users with atleast 3 columns id, user_id, type if existing database is not writable and then after validating user, I will create token for new table's id columns.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 HK Softtronix