laravelresponselaravel-7

Laravel 7 : Make failed validation response 200 instead of 422


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?


Solution

  • 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