Skip to content
Advertisement

Return JSON details of failed validation with Laravel 8

I’m creating an endpoint to store an Office with two fields: name, address. When validation fails laravel returns status 200 and a welcome page. It should return 4xx and error details with JSON, shouldn’t it? I tried to catch an exception (ValidationError) but I don’t get the error details.

JavaScript

I’m testing it with unit test and postman:

JavaScript

and with postman the content-type is application/json

EDITED Postman was messing up the headers. httpie and curl get the correct response with this code and the accepted answer’s.

Advertisement

Answer

You can use Validator instead like so

JavaScript

Or you can use validator() helper method

JavaScript

This will automatically validate and response back with errors and it also, works with web and api endpoints.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement