sajadsholi
sajadsholi

Reputation: 341

change the format of laravel API Errors and Exceptions

I write api for the applications with laravel.

for example I have two field which are "city_id" and "address" and I validate them with these rules :

$request->validate([
    'city_id' => 'bail|required|numeric',
    'address' => 'required'
]);

if validation fails the response will be :

{
"message": "The given data was invalid.",
"errors": { 
    "city_id": ["The city id field is required."]
  }
}

everything is fine but I want change the validation error at api response to this :

{
 "msg" => 'The city id field is required.'
}

actually I want send one error without the key . where can I change that?

Upvotes: 0

Views: 397

Answers (1)

Alisher Gafurov
Alisher Gafurov

Reputation: 447

You can write/modify the Laravel exceptions handler. Here you can read more about it here https://laravel.com/docs/5.8/errors or here https://laravel.com/docs/6.x/errors (depends what version of Laravel you using)

Example:

class Handler extends ExceptionHandler
{   

    ...

    public function render($request, Exception $e)
    {
       if ($exception instanceof ValidationException) {
           return new JsonResponse(
                  ['msg' => $e->getMessage()],
                  400
           );
       }
    }

    ...

}

Upvotes: 1

Related Questions