我有一个注册用户路线,需要name
,email
和password
。如果数据正确,即存在唯一的电子邮件和参数,则它可以正常工作,但如果用户已经注册,则Laravel会以自己的格式发送自动错误消息。我希望返回格式在成功或失败的情况下保持一致。
成功注册返回数据:
{
"status": "success",
"token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjUsImlzcyI6Imh0dHA6Ly8xMjcuMC4wLjE6ODAwMC9hcGkvYXV0aC9yZWdpc3RlciIsImlhdCI6MTUyMTI3NTc5MiwiZXhwIjoxNTIxMjc5MzkyLCJuYmYiOjE1MjEyNzU3OTIsImp0aSI6Ik1wSzJSYmZYU1dobU5UR0gifQ.fdajaDooBTwP-GRlFmAu1gtC7_3U4ygD1TSBIqdPHf0"
}
但如果出现错误,它会以其他格式发送数据。
{"message":"The given data was invalid.","errors":{"email":["The email has already been taken."]}}
我希望他们两个都保持一致。成功返回数据很好。但我想在发生故障时自定义数据。像这样:
{"status":"error","message":"The given data was invalid.","errors":{"email":["The email has already been taken."]}}
基本上,我需要status
param随每个回复而来。
另外,我在使用Postman时有一个查询,输出是纯HTML,当发生错误时HTML页面是默认的Laravel页面,另一方面当angular发送相同的请求时,错误是json格式,我刚刚粘贴在上面。 因为角度在任何情况下都得到JSON,所以对我来说这很好。但是为什么邮递员没有向我展示这种反应。
注册控制器:
public function register(RegisterRequest $request)
{
$newUser = $this->user->create([
'name' => $request->get('name'),
'email' => $request->get('email'),
'password' => bcrypt($request->get('password'))
]);
if (!$newUser) {
return response()->json(['status'=>'error','message'=>'failed_to_create_new_user'], 500);
}
return response()->json([
'status' => 'success',
'token' => $this->jwtauth->fromUser($newUser)
]);
}
注册请求处理程序:
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'name' => 'required',
'email' => 'required | email | unique:users,email',
'password' => 'required'
];
}
答案 0 :(得分:1)
如果我理解正确,您总是会在没有“状态”的情况下得到错误回复。键。
您当前的代码会发生什么,有几件事情:
结论:当您的验证规则不符合时,您的代码甚至无法触发。
我已经研究过一个解决方案并提出了这个问题:
public function register(Illuminate\Http\Request $request)
{
//Define your validation rules here.
$rules = [
'name' => 'required',
'email' => 'required | email | unique:users,email',
'password' => 'required'
];
//Create a validator, unlike $this->validate(), this does not automatically redirect on failure, leaving the final control to you :)
$validated = Illuminate\Support\Facades\Validator::make($request->all(), $rules);
//Check if the validation failed, return your custom formatted code here.
if($validated->fails())
{
return response()->json(['status' => 'error', 'messages' => 'The given data was invalid.', 'errors' => $validated->errors()]);
}
//If not failed, the code will reach here
$newUser = $this->user->create([
'name' => $request->get('name'),
'email' => $request->get('email'),
'password' => bcrypt($request->get('password'))
]);
//This would be your own error response, not linked to validation
if (!$newUser) {
return response()->json(['status'=>'error','message'=>'failed_to_create_new_user'], 500);
}
//All went well
return response()->json([
'status' => 'success',
'token' => $this->jwtauth->fromUser($newUser)
]);
}
现在,不符合您的验证规则仍会触发错误,但是您的错误,而不是laravel的内置错误:)
我希望它有所帮助!
答案 1 :(得分:1)
在 Laravel 8 中,我添加了我的自定义 invalidJson 并带有 "success": false:
在 app/Exceptions/Handler.php 中:
/**
* Convert a validation exception into a JSON response.
*
* @param \Illuminate\Http\Request $request
* @param \Illuminate\Validation\ValidationException $exception
* @return \Illuminate\Http\JsonResponse
*/
protected function invalidJson($request, ValidationException $exception)
{
return response()->json([
'success' => false,
'message' => $exception->getMessage(),
'errors' => $exception->errors(),
], $exception->status);
}
答案 2 :(得分:0)
这是我想出来的:
function validate(array $rules)
{
$validator = Validator::make(request()->all(), $rules);
$errors = (new \Illuminate\Validation\ValidationException($validator))->errors();
if ($validator->fails()) {
throw new \Illuminate\Http\Exceptions\HttpResponseException(response()->json(
[
'status' => false,
'message' => "Some fields are missing!",
'error_code' => 1,
'errors' => $errors,
], \Illuminate\Http\JsonResponse::HTTP_UNPROCESSABLE_ENTITY));
}
}
创建一个辅助目录 (App\Helpers
) 并将其添加到文件中。不要忘记将其添加到您的 composer.json 中
"autoload": {
"files": [
"app/Helpers/system.php",
],
},
现在您可以在控制器中调用 validate()
并获得您想要的:
validate([
'email' => 'required|email',
'password' => 'required|min:6|max:32',
'remember' => 'nullable|boolean',
'captcha' => 'prod_required|hcaptcha',
]);