简体   繁体   中英

Laravel API: Throw not found error if user not exist in database Laravel

I have a login/register API and when the user tries to login with the wrong email/password and with credentials that don't exist in the database, they produce the same response which is this:

在此处输入图像描述

What I want to do is separate the responses; When the user tries to login with the wrong email/password, 'Invalid Credentials' will be the response and when the user tries to login with credentials that don't exist in the database, the response should be 'User Does Not Exist!'

This is my code in the login controller:

 $loginData = $request->validate([
            'email' => 'email|required',
            'password' => 'required',
        ]);

        if (!auth()->attempt($loginData)) {
            return response(['message' => 'Invalid Credentials']);
        }

You can use any columns as an action for the authentication process. According to the documentation,

The attempt method will return true if authentication was successful. Otherwise, false will be returned.

And you can apply conditions as many you want inside the attempt method by passing array of columns like.

if (Auth::attempt(['email' => $email, 'password' => $password, 'active' => 1])) {
    // The user is active, not suspended, and exists.
}

So here we reached at a conclusion that, we can use this method to determine that if specific user exists in database by matching different columns.

Therefor, we can use the same attempt method for different purposes. like for checking if only email exists in database like,

if (! Auth::attempt(['email' => $email])) {
    // user doesn't exists in database 
}

and so on. Further, if this scenario doesn't work, you may use eloquent or DB Builder just for special purpose besides from email/password authentication action.

Thanks mate,

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM