Laravel 7 : Make failed validation response 200 instead of 422

Viewed 1827

I'm creating a Laravel 7 application.

I have created a POST API that accepts 2 parameters and added validation on them. When validator fails, it gives response "422 unprocessable entity" and gives an error in JSON format like this :

{
    "message": "The given data was invalid.",
    "errors": {
        "mobile_no": [
            "The mobile no must be 10 digits."
        ]
    }
}

Now I want the same response with error code 200 instead of 422.

How should I achieve this?

2 Answers

You can use an error handler for this purpose. https://laravel.com/docs/7.x/errors#render-method

 public function render($request, Exception $exception)
 {
     if ($condition)) {
       return response()->json($content, 200);
     }

    return parent::render($request, $exception);
}

Check inside function exception you need and replace it with successful response

For laravel 8, i override method invalidJson in app/Exceptions/Handler.php

protected function invalidJson($request, ValidationException $exception)
{
    return response()->json([
        'message' => $exception->getMessage(),
        'errors' => $exception->errors(),
    ], 200); //parent method return 422
}
Related