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?
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