Duy Nguyen Tho
Duy Nguyen Tho

Reputation: 47

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

Upvotes: 0

Views: 7457

Answers (3)

rocknrold
rocknrold

Reputation: 66

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 Illuminate\Http\Exceptions\HttpResponseException;
use Illuminate\Contracts\Validation\Validator;

    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]

Upvotes: 3

user16957038
user16957038

Reputation:

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',
    ]
],

Upvotes: 0

A.A Noman
A.A Noman

Reputation: 5270

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'
    ]
);

Upvotes: 3

Related Questions