Laravel 5.2 - Validation with API

2019-05-24 06:20发布

问题:

I am using Laravel 5.2 for validation with a REST JSON API.

I have a UserController that extends Controller and uses the ValidatesRequests trait.

Sample code:

$this->validate($request, [
    'email'         => 'required|email',
    'password'      => 'required|min:4|max:72',
    'identifier'    => 'required|min:4|max:36',
    'role'          => 'required|integer|exists:role,id',
]);

This throws an exception, so in my Exceptions/Handler.php I have this code:

public function render($request, Exception $e)
{
   return response()->json([
       'responseCode'  => 1,
       'responseTxt'   => $e->getMessage(),
   ], 400);
}

However, when validating responseTxt is always:

Array
(
   [responseCode] => 1
   [responseTxt] => The given data failed to pass validation.
)

I have used Laravel 4.2 in the past and remember the validation errors providing more detail about what failed to validate.

How can I know which field failed validation and why?

回答1:

In Laravel 5.2 validate() method throws a Illuminate\Validation\ValidationException, so if you want to get the response use getResponse() instead getMessage().

For example, an easy way to handle this exception could be doing something like this:

try{
   $this->validate($request, [
       'email'         => 'required|email',
       'password'      => 'required|min:4|max:72',
       'identifier'    => 'required|min:4|max:36',
       'role'          => 'required|integer|exists:role,id'
   ]);
}catch( \Illuminate\Validation\ValidationException $e ){
    return $e->getResponse();
}


回答2:

A ValidationException gets thrown which gets rendered as a single generic message if the request wants JSON.

Instead of using the validate() method, manually invoke the validator, e.g.:

$validator = Validator::make($request->all(), [
    'email'         => 'required|email',
    'password'      => 'required|min:4|max:72',
    'identifier'    => 'required|min:4|max:36',
    'role'          => 'required|integer|exists:role,id',
]);
if ($validator->fails()) {
    return new JsonResponse(['errors' => $validator->messages()], 422);
}

https://laravel.com/docs/5.2/validation#manually-creating-validators

As an aside, I'd recommend a 422 HTTP status code rather than a 400. A 400 usually implies malformed syntax. Something that causes a validation error usually means that the syntax was correct, but the data was not valid. 422 means "Unprocessable Entity" https://tools.ietf.org/html/rfc4918#section-11.2