简体   繁体   中英

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.

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

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()

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).

Then the mobile app developers can access the httpCode from response

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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