Laravel表单请求验证消息用于REST API

3

如何从表单请求中返回所需错误、无效错误和最小/最大错误的不同代码?我正在使用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));
}

但我需要检测它是必需错误、已存在错误、无效格式错误还是最小/最大值错误。

如何完成这个任务?

2个回答

1

您可以使用$validator->messages()添加额外的信息。

就像这样:

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

0

不要抛出新的HttpResponseException,而是返回一个新的JsonResponse($data, $httpCode)。

这样移动应用程序开发人员就可以从响应中访问httpCode了。

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接