Home > Back-end >  exists validation is not working in laravel
exists validation is not working in laravel

Time:07-24

LoginController

 public function login(Request $request)
    {
        $request->validate([
            'email'=>'required|exists:users',
            'password'=>'required|exists:users',
        ]);
        $email=$request->email;
        $password=$request->password;
        
        if (Auth::attempt(['email' => $email, 'password' => $password,'role'=>'admin'])) {
            $token = $request->user()->createToken($request->email)->plainTextToken;
            return response([
                'token'=>$token,
                'message'=>'Admin logged in successfully',
            ],200);
        }
        
        if (Auth::attempt(['email' => $email, 'password' => $password,'role'=>'user'])) {
            $token = $request->user()->createToken($request->email)->plainTextToken;
            return response([
                'token'=>$token,
                'message'=>'User logged in successfully',
            ],200);
        }
            return response([
                'message'=>'Email or password is wrong',
            ],401);

    }

I am creating a login API. So, I want to show email is wrong and password is wrong if the user or admin enters wrong email and wrong password. Here, when I enter the correct email and wrong password it displays only password is wrong error which is ok but when I enter the wrong email and correct password it shows two error messages that the email is wrong and the password is wrong. It should have shown only email is wrong error but why it is showing two errors can anyone explain it to me?

CodePudding user response:

There are two type of validation rules in the laravel docs for this type of case.

  1. exists - The field under validation must exist in a given database table.
'email' => 'exists:users,email'
  1. unique - The field under validation must not exist within the given database table.
'email' => 'unique:users,email'

In both case specify the column name with a comma.

CodePudding user response:

You cannot use exists in this way for checking the password. All you can do is check that it has been provided.

'password'=>'required|exists:users',

This will check that the supplied value is present in the password field of ANY user. Since the passwords are hashed, it would never match any user, never mind the user being checked.

As a security point, you should not indicate which of the items is wrong because this is a weakness and tells the person accessing the API that they have correctly guessed a username or a password.

Change both validations to required only and leave the Auth::attempt() to do the rest, returning the 401 if the credentials are not matched.

  • Related