-1

I have a Laravel API that returns JSON responses to the client. By default, Laravel sends error messages in a standard format, such as 422 Unprocessable Entity. However, I want to send custom error messages to the client in a specific format, for example:

{
    "status": "error",
    "message": "Invalid email address"
}

I have tried using the abort function with a custom status code and message, but this does not send the response in the desired format. How can I send custom error messages to the client in the format shown above?

matiaslauriti
  • 7,065
  • 4
  • 31
  • 43
HexxonDiv
  • 11
  • 1
  • 8
  • I [wrote a library](https://github.com/MarcinOrlowski/laravel-api-response-builder) that allows you to have normalized JSON responses, incl. errors. – Marcin Orlowski May 07 '23 at 17:04
  • Actually, by default Laravel outputs a 422 status code but the content of the response is an array of errors including a meaningful message. You can also customize your error messages in several ways. https://laravel.com/docs/10.x/validation#working-with-error-messages – Elias Soares May 07 '23 at 17:05

1 Answers1

3

Many possible solutions for you. Have a look at this discussion for example.

You can create your own validators, or just extend on the existing ones built in Laravel. Also, it's very possible to return whatever else you need with for example:

return response()->json(['status' => 'error', 'message' => 'Your message here'], 422);

But if you need it for validation, I would recommend other previously mentioned steps as they follow a more standardized "good practice" approach.

Also, when sending the request, make sure you set the following header:

Accept:application/json

You can also "force" that header using a middleware in Laravel if needed. Link here