How to custom message validator with Laravel - 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

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]

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

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

Related

How to make 2 different Laravel Validation messages for the same rule that has 2 different arguments?

Hello I have Laravel validation request with these rules
public function rules()
{
return [
'email' => 'unique:users,email|required|unique:invitations,email',
'name' => 'string|required',
];
}
I want that "unique:users,email" would display one message and "unique:invitations,email" display other message. How to do that?
'unique:users,email' => 'This E-Mail address is already registered.',
'unique:invitations,email' => 'Invitation to this E-Mail address is already sent.',
It always returns default message for "unique" rule.
'unique' => 'The :attribute has already been taken.',
I am not sure if this will work but can you try these
public function messages()
{
return [
'unique:users,email' => 'This E-Mail address is already registered.',
'unique:invitations,email' => 'Invitation to this E-Mail address is already sent.',
//or
'email.unique:users,emai' => 'This E-Mail address is already registered.',
'email.unique:invitations,email' => 'Invitation to this E-Mail address is
//you may even try it without the ,fieldname
'email.unique:users' => ''
];
}
Try to define like
'email.unique:users,emai' => ....,
'email.unique:invitations,emai' => ....,

Laravel validation messages contain "validation." instead of custom error message

I have a function that does some validation. Instead of $errors->get(key) returning the custom error messages I've defined, I'm getting the validation rule name. For example, if I use an email that's not unique:
$messages = [
'new_email.required' => 'Your new email address is required.',
'new_email:unique' => 'That email is already in use.',
'current_password|required' => 'Your current password must be provided.'
];
$rules = [
'new_email' => 'required|email|unique:users,email,' . $user->id,
'current_password' => 'required',
];
$validator = Validator::make($request->all(), $rules, $messages); // <-- custom error messages passed in here
if ($validator->fails()) {
$errors = $validator->errors();
if ($errors->has('new_email')) {
$msg = $errors->get('new_email'); // $msg contains ['validation.unique'] instead of ['That email is already in use.']
...
}
}
$errors->get('new_email') returns ['validation.unique'] instead of the custom error message in the array that's passed as the 3rd parameter to Validator::make. How can I get the custom error message instead of the validation rule that has been broken by the request?
There are some similar questions to this, but all the answers seem to focus on the resource/lang/xx/validation.php file missing or something like that. I'm not using those localization features at all.
Based on the documentation you should set your message with a string between property and validation rule.
$messages = [
'new_email.unique' => 'That email is already in use.',
];

laravel validation to check multi dimensional array

I have two fields
data[0][student]
data[0][teacher]
data[1][student]
data[1][teacher]
I tried this rule
$rules['data.*.student'] = 'required';
which gives this error
{
"error": {
"status_code": 412,
"validation": {
"data.student.*": [
"The data.*.student field is required."
]
},
"message": "Validation Failed"
}
}
how can I achieve this and make fields required if user missed this input field
data[student][0]?
For that you need to set a custom messages for rules inside Formrequest file.
You need to add rules and messages function Like this demostrated example:
Rules
public function rules()
{
return [
'item.*.name' => 'required|string|max:255',
'item.*.description' => 'sometimes|nullable|string|min:60',
'sku' => 'required|array',
'sku.*' => 'sometimes|required|string|regex:​​/^[a-zA-Z0-9]+$/',
'sku' => 'required|array',
'price.*' => 'sometimes|required|numeric'
];
}
Message
public function messages()
{
return [
'item.*.name.required' => 'You must have an item name.',
'item.*.name.max' => 'The item name must not surpass 255 characters.',
'item.*.description.min' => 'The description must have a minimum of 60 characters.',
'sku.*.regex' => 'The SKU must only have alphanumeric characters.',
'price.*.numeric' => 'You have invalid characters in the price field.'
];
}

How to use custom translations for requests in Laravel?

Documentation says to create directory with file by path: resources/lang/xx/validation.php.
Then add content of validation words:
return ['custom' => [
'email' => [
'required' => 'We need to know your e-mail address!',
],
]];
How to use this for Creating Form Requests where is going validation?
This is just for deploying custom validation messages, e.g. whenever 'email' is 'required' it will return this message in place of the default message: The email field is required.
If you want to replace all the other messages take a look at /resources/lang/en/validation.php here and see all the basic messages which you can replace with your local language versions in your /resources/lang/xx/validation.php
If you want a custom message, find the custom array at line 130 and change to:
'custom' => [
'price' => [
'required' => 'The price is required! Please supply one.',
],
],
Then, be sure to set your app locale, e.g.
Route::get('welcome/{locale}', function ($locale) {
App::setLocale($locale);
//
});
Or if your entire app is in another language, you could set locale in your /config/app.php on line 81.
Your usual validator will now use the messages in /resources/lang/locale/validation.php

Change, error response displays a single error message in Laravel 5.4

I am using required_without validation for required any one field.
return Validator::make($data, [
'user_email' => 'required_without:user_phone|email',
'user_phone' => 'required_without:user_email|min:10',
'country_code' => 'required_with:user_phone',
'otp' => 'required|numeric|max:6',
]);
And How to user Unique for check email or phone registered or not in my tbl_users
And I have got this error message,I want to display one one line for user_email or user_phone.
And I am using country_code if user_phone.
I have got these error messages in response.
{
"user_email": [
"The user email field is required when user phone is not present."
],
"user_phone": [
"The user phone field is required when user email is not present."
]
}
i want this type of error message with s, Like :
{
"status":false,
"message":"Please enter email or phone"
}
You can use third param to add message manually, remove required_without for user_email and keep it for user_phone
$messages = [
'user_phone.required_without' => 'Please enter email or phone',
]
return Validator::make($data, [
'user_email' => 'user_phone|email',
'user_phone' => 'required_without:user_email|min:10',
'country_code' => 'required_with:user_phone',
'otp' => 'required|numeric|max:6',
],$messages);
Now you will get error message for only user_phone as Please enter email or phone

Resources