如何为表单请求中的必需错误,无效错误和最小最大错误返回不同的代码?我正在使用failedValidation方法。
使用API的移动应用需要显示已翻译的错误消息 并且它仅使用api返回的错误代码而不是消息,因此需要针对所需的错误,无效错误和最小最大错误以及已经存在的错误将代码分开
下面是我在表单请求中的代码
/**
* Handle a failed validation attempt.
*
* @param \Illuminate\Contracts\Validation\Validator $validator
* @return void
*
* @throws \Illuminate\Validation\ValidationException
*/
protected function failedValidation(Validator $validator)
{
$errors = (new ValidationException($validator))->errors();
throw new HttpResponseException(response()->json(['code'=> 'VALIDATION_ERROR','errors' => $errors
], JsonResponse::HTTP_UNPROCESSABLE_ENTITY));
}
但是我需要检测它是否是必需的错误或已经存在的错误或有效格式错误或最小最大错误。
这怎么办?
答案 0 :(得分:1)
您可以使用$validator->messages()
所以会是这样:
throw new HttpResponseException(response()->json([
'code'=> 'VALIDATION_ERROR',
'errors' => $errors,
'messages' => $validator->messages()->toArray()
], JsonResponse::HTTP_UNPROCESSABLE_ENTITY));
答案 1 :(得分:0)
不是抛出新的HttpResponseException,而是返回新的JsonResponse($ data,$ httpCode)。
然后,移动应用程序开发人员可以从响应中访问httpCode
return new JsonResponse([
'code'=> 'VALIDATION_ERROR',
'errors' => $errors
], JsonResponse::HTTP_UNPROCESSABLE_ENTITY);