How to custom message validator with Laravel

I am making an API that allows users to input some information like email, phone number, address …
But if users input wrong phone nums, the validate error is

{
  "message": "The given data was invalid.",
  "errors": {
    "phone": [
      "The phone has already been taken."
    ]
  }
}

As you can see the message returns is
"message": "The given data was invalid."

. But the message I expect is The phone has already been taken. How can I custom the message as I expect? With an email validator, the message is the same but the key is email. The message I expect is
"message": "The ... has already been taken. "

I’m using laravel 8 and validate in Request
Example a function rules()
    public function rules()
    {
        return [
            'profile_img' => 'nullable|image|mimes:jpeg,png,jpg,gif,svg|max:' . config('filesystems.max_upload_size'),
            'name' => 'nullable|min:3',
            'phone' => [
                'required',
                'numeric',
                new UpdatePhoneRule(User::TYPE_CLIENT),
            ],
            'email' => [
                'nullable',
                'email',
                new UpdateEmailRule(User::TYPE_CLIENT),
            ]
        ];
    }

Thanks

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

On the Request php file you can use this function failedValidation() and pass in a Validator. This way you can alter or customize the response if validation fails.

use IlluminateHttpExceptionsHttpResponseException;
use IlluminateContractsValidationValidator;

    protected function failedValidation(Validator $validator) {
        throw new HttpResponseException(response()->json(['status'=>'failed',
                                                    'message'=>'unprocessable entity',
                                                    'errors'=>$validator->errors()->all()], 422));
    }

Sample response is here..
{
"status": "failed",
"message": "unprocessable entity",
"errors": [
    "The name must be a string.",
    "One or more users is required"
 ]
}

As you can see the message is changed now you can do whatever you want on the response message.

Also you can try this

$validator->errors()->messages()[keyname]

Method 2

You have to use unique in your validation

$this->validate(
    $request, 
    [   
        'email'             => 'required|unique:your_model_names',
        'phone'             => 'required|unique:your_model_names'
    ],
    [   
        'email.required'    => 'Please Provide Your Email Address For Better Communication, Thank You.',
        'email.unique'      => 'Sorry, This Email Address Is Already Used By Another User. Please Try With Different One, Thank You.',
        'phone.required' => 'Your custom message',
        'phone.unique'      => 'The phone has already been taken'
    ]
);

Method 3

You can do this in the lang file: resources/lang/en/validation.php. If all you want to do is change, for example, the message for a unique rule on an email field across the entire app you can do:

/*
|--------------------------------------------------------------------------
| Custom Validation Language Lines
|--------------------------------------------------------------------------
|
| Here you may specify custom validation messages for attributes using the
| convention "attribute.rule" to name the lines. This makes it quick to
| specify a specific custom language line for a given attribute rule.
|
*/

'custom' => [
    'attribute-name' => [
        'rule-name' => 'custom-message',
    ],
    'email' => [
        'unique' => 'This email is already registered...etc',
    ]
],


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x