Chris
Chris White Web Developer

Laravel API Form Request Validation Errors

1 February 2017 ~1 minute read

This is a quick tip post about a nice way to format your validation errors when working with a Laravel API.

If you’re using Laravel’s Form Requests in the context of an API, you’ll know that by default the validation errors are chucked back to the client like this:

1{
2 "username": [
3 "The username field is required."
4 ],
5 "password": [
6 "The password field is required."
7 ]
8}

While the above is a pretty sensible default format, it might be inconsistent with the rest of your API and thus cause confusion with your API consumers.

To build our own output, we’re going to implement our own FormRequest class that extends Laravel’s. Place it in the app/Http/Requests directory.

1<?php
2 
3namespace App\Http\Requests;
4 
5use Illuminate\Foundation\Http\FormRequest as LaravelFormRequest;
6use Illuminate\Http\JsonResponse;
7 
8abstract class FormRequest extends LaravelFormRequest
9{
10 /**
11 * Get the validation rules that apply to the request.
12 *
13 * @return array
14 */
15 abstract public function rules();
16 
17 /**
18 * Get the failed validation response for the request.
19 *
20 * @param array $errors
21 * @return JsonResponse
22 */
23 public function response(array $errors)
24 {
25 $transformed = [];
26 
27 foreach ($errors as $field => $message) {
28 $transformed[] = [
29 'field' => $field,
30 'message' => $message[0]
31 ];
32 }
33 
34 return response()->json([
35 'errors' => $transformed
36 ], JsonResponse::HTTP_UNPROCESSABLE_ENTITY);
37 }
38}

Now, instead of your form request’s extending Illuminate\Foundation\Http\FormRequest, have them extend your FormRequest class. When the form request validation fails, you’ll receive an output like this instead:

1{
2 "errors": [
3 {
4 "field": "username",
5 "message": "The username field is required."
6 },
7 {
8 "field": "password",
9 "message": "The password field is required."
10 }
11 ]
12}

In my case, this was consistent with the rest of the error responses in the API. Your needs may vary, so feel free to change that response method as you see fit. And if you’re one of the heathens that uses 400 Bad Request for validation errors, use JsonResponse::HTTP_BAD_REQUEST. And then change it to the correct status code: JsonResponse::HTTP_UNPROCESSABLE_ENTITY.

Made with Jigsaw and Torchlight. Hosted on Netlify.