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.

    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required',
            'address' => 'required'
        ]);
        // if validation failed, 4xx?

        // logic to create a model here
        return $office; // everything fine, 201 and object details
    }

I’m testing it with unit test and postman:

    public function testValidationFailed()
    {
        $payload = [
            "wrongfield" => "Example Name"
        ];

        $response = $this->postJson('/api/offices/', $payload);

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

$validator = Validator::make($request->all(), [
      'name' => 'required',
      'address' => 'required'
]);

if ($validator->fails()) {
   return response()->json($validator->errors(), 404);
}

Or you can use validator() helper method

validator($request->all(), [
    'name' => 'required',
    'address' => 'required'
])->validate();

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