简体   繁体   English

laravel表单请求验证消息为rest api

[英]laravel form request validation messages for rest api

how to return different code for required errors, invalid errors and min max errors from form request ? 如何从表单请求返回所需错误,无效错误和最小错误的不同代码? i am using failedValidation method. 我正在使用failedValidation方法。

the mobile app that consumes the API need to show translated error messages and its only using the error code return by the api not the message so need to separate the code for required errors, invalid errors and min max errors and already exist errors 使用API​​的移动应用程序需要显示已翻译的错误消息,并且仅使用api返回的错误代码而不是消息,因此需要将代码分开以获取所需错误,无效错误和最小错误以及已存在的错误

below is my code in form request 下面是我在表单请求中的代码

/**
 * 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));
}

But i need to detect whether its a required error or already exist error or in valid format error or min max error. 但我需要检测它是否是必需的错误或已存在错误或有效格式错误或最小最大错误。

How can this be done? 如何才能做到这一点?

you can add additional information using $validator->messages() 您可以使用$validator->messages()添加其他信息

so it would be like this: 所以它会是这样的:

throw new HttpResponseException(response()->json([
   'code'=> 'VALIDATION_ERROR',
   'errors' => $errors, 
   'messages' => $validator->messages()->toArray()
], JsonResponse::HTTP_UNPROCESSABLE_ENTITY));

Instead throwing a new HttpResponseException, return a new JsonResponse($data, $httpCode). 而是抛出一个新的HttpResponseException,返回一个新的JsonResponse($ data,$ httpCode)。

Then the mobile app developers can access the httpCode from response 然后,移动应用程序开发人员可以从响应中访问httpCode

return new JsonResponse([
  'code'=> 'VALIDATION_ERROR',
  'errors' => $errors
], JsonResponse::HTTP_UNPROCESSABLE_ENTITY);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM