Customize $message when validation failed on `unique`?
I am building a JSON API and when creating a user, I have form request validation that declares
'email' => [
'unique:users'
],
When trying to create a user that already exists, I receive
{"message":"The given data was invalid.","errors":{"email":["The email has already been taken."]}}
This is a poor experience for the user on the front-end as I have it set up to render all message at the bottom of the form.
Ideally I would display An account already exists at the bottom of the form, not as the inline email field message.
How do I selectively override the message returned when using form request validation?
Cheers!
@CRONIX - Hi the Original Question is " I am building a JSON API", so your response applies to web response with html Tags, API needs json response.
the Best way to respond with errors in API is to throw an exception and add your exception with what ever message you want to return. BTW that's where you are getting the message ( The given data was invalid ) from, as the validation is using this exception from Laravel exceptions.
class EmailExistsException extends Exception
{
public $httpStatusCode = SymfonyResponse::HTTP_BAD_REQUEST;
public $message = 'An account already exists.';
}
So I would us e something like this in controller
$validator = Validator::make($request->all(), [
'unique:users'
]);
if ($validator->fails()) {
throw new EmailExistsException();
}
Please or to participate in this conversation.