Laravel API Form Request validation errors


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:

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.

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:

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.

About the author


Chris is a software engineer from Scotland. He can usually be found working on web applications for Intouch Insight using Laravel and Angular, but tends to dabble a lot with other technologies in his free time.

Recent Posts