Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

tommybuns's avatar

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!

0 likes
5 replies
tommybuns's avatar

That works great to override the field level validation message, but not the over all $message that is sent back, that is still "The given data was invalid." no matter what you set public function messages() to.

Any ideas how to override the "The given data was invalid." message, specifically?

Shaden's avatar

Try This

 $validator = Validator::make($request->all(), [
           'unique:users'
        ]);

        if ($validator->fails()) {
            $message = ' User is not Unique    OR Any Message You want';
            return view('Your View')->withErrors($message);
        }

I guess if you want to return the error in API you need to json encode and return,

1 like
Shaden's avatar
Shaden
Best Answer
Level 4

@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.