如何从表单请求返回所需错误,无效错误和最小错误的不同代码?我正在使用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));
}
但我需要检测它是否是必需的错误或已存在错误或有效格式错误或最小最大错误。
如何才能做到这一点?
您可以使用$validator->messages()
添加其他信息
所以它会是这样的:
throw new HttpResponseException(response()->json([
'code'=> 'VALIDATION_ERROR',
'errors' => $errors,
'messages' => $validator->messages()->toArray()
], JsonResponse::HTTP_UNPROCESSABLE_ENTITY));
而是抛出一个新的HttpResponseException,返回一个新的JsonResponse($ data,$ http代码)。
然后,移动应用程序开发人员可以从响应中访问httpCode
return new JsonResponse([
'code'=> 'VALIDATION_ERROR',
'errors' => $errors
], JsonResponse::HTTP_UNPROCESSABLE_ENTITY);