Laravel API: 如果数据库中不存在用户则抛出未找到错误 Laravel
Laravel API: Throw not found error if user not exist in database Laravel
我有一个 login/register API,当用户尝试使用错误的 email/password 和数据库中不存在的凭据登录时,他们会产生相同的响应这是:
我想做的是将响应分开;当用户尝试使用错误的 email/password 登录时,将响应 'Invalid Credentials'
并且当用户尝试使用数据库中不存在的凭据登录时,响应应为 'User Does Not Exist!'
这是我在登录控制器中的代码:
$loginData = $request->validate([
'email' => 'email|required',
'password' => 'required',
]);
if (!auth()->attempt($loginData)) {
return response(['message' => 'Invalid Credentials']);
}
您可以使用任何列作为身份验证过程的操作。根据文档,
The attempt method will return true if authentication was successful.
Otherwise, false will be returned.
并且您可以通过传递列数组在 attempt 方法中应用任意数量的条件,例如。
if (Auth::attempt(['email' => $email, 'password' => $password, 'active' => 1])) {
// The user is active, not suspended, and exists.
}
所以这里我们得出一个结论,我们可以使用这种方法通过匹配不同的列来判断特定用户是否存在于数据库中。
因此,我们可以针对不同的目的使用相同的attempt方法。比如检查 只有电子邮件 存在于数据库中,比如
if (! Auth::attempt(['email' => $email])) {
// user doesn't exists in database
}
等等。此外,如果这种情况不起作用,除了 email/password 身份验证操作之外,您还可以使用 eloquent 或 DB Builder 仅用于特殊目的。
谢谢伙计,
我有一个 login/register API,当用户尝试使用错误的 email/password 和数据库中不存在的凭据登录时,他们会产生相同的响应这是:
我想做的是将响应分开;当用户尝试使用错误的 email/password 登录时,将响应 'Invalid Credentials'
并且当用户尝试使用数据库中不存在的凭据登录时,响应应为 'User Does Not Exist!'
这是我在登录控制器中的代码:
$loginData = $request->validate([
'email' => 'email|required',
'password' => 'required',
]);
if (!auth()->attempt($loginData)) {
return response(['message' => 'Invalid Credentials']);
}
您可以使用任何列作为身份验证过程的操作。根据文档,
The attempt method will return true if authentication was successful. Otherwise, false will be returned.
并且您可以通过传递列数组在 attempt 方法中应用任意数量的条件,例如。
if (Auth::attempt(['email' => $email, 'password' => $password, 'active' => 1])) {
// The user is active, not suspended, and exists.
}
所以这里我们得出一个结论,我们可以使用这种方法通过匹配不同的列来判断特定用户是否存在于数据库中。
因此,我们可以针对不同的目的使用相同的attempt方法。比如检查 只有电子邮件 存在于数据库中,比如
if (! Auth::attempt(['email' => $email])) {
// user doesn't exists in database
}
等等。此外,如果这种情况不起作用,除了 email/password 身份验证操作之外,您还可以使用 eloquent 或 DB Builder 仅用于特殊目的。
谢谢伙计,