我正在使用Lumen和Dingo API来构建API。我的注册功能检查指定的电子邮件是否已存在。
如果数据库中已存在电子邮件,则使用Dingo API Helpers返回错误响应。
Dingo\Api\Routing\Helpers
isEmailTaken函数:
private function isEmailtaken($email) {
$userExists = User::where('email', $email)->count();
if($userExists) {
$return['error'] = true;
$return['message'] = "It appears you already have an account with us.";
return $return;
} else {
$return['error'] = false;
return $return;
}
}
注册函数调用该函数并返回错误:
$validateEmail = $this->isEmailtaken($email);
if ($validateEmail['error'] == true) {
return $this->response->errorBadRequest($validateEmail['message']);
}
它在json响应中输出正确的错误消息并带有正确的错误代码:
"{"message":"It appears you already have an account with us.","status_code":400}"
但是,标题中响应生成的状态为OK,代码为200。
答案 0 :(得分:0)
status_code 400 bad request
将在请求数据无效时返回
下面的代码有助于返回自定义status_code的响应
use Illuminate\Http\Response;
return response()->json(['message' => 'It appears you already have an account with us.'])->setStatusCode(400);
另一种从laravel验证验证唯一emailID的简短方法,如下所示
$rules = array(
'email'=>'required|email|unique:user',
);
$validator = Validator::make($request->all(), $rules);
if (!$validator->passes()) {
return response()->json([ 'message' => $validator->messages()])->setStatusCode(400);
}