Laravel make custom error validation messages - laravel

Greeting, this is my code and I need to make custom error messages for every rule
$validator = Validator::make($request->all(), [
'name' => 'required|min:3|max:100',
'phone' => 'required',
'date' => 'required',
'address' => 'required|min:3|max:100',
'test' => 'required|min:3|max:100',
]);
if ($validator->fails()) {
$errors = $validator->errors();
return response()->json($errors);
}

Its better to create a separate request for validation purpose
public function rules(): array
{
return [
'name' => 'required|min:3|max:100',
'phone' => 'required',
'date' => 'required',
'address' => 'required|min:3|max:100',
'test' => 'required|min:3|max:100',
]
}
public function messages(): array
{
return [
'name' => 'Please enter name'
];
}

you can create your own custom validation messages in two ways:
1- in resources/lang/en/validation.php you can change the validation message for every rule
2- you can pass your custom message for each validation like this:
$validator = Validator::make($input, $rules, $messages = [
'required' => 'The :attribute field is required.',
]);
you can check here for more information
specific to your question:
$messages = [
'required' => 'The :attribute field is required.',
'min' => ':attribute must be more than 3 chars, less than 100'
]
$validator = Validator::make($request->all(), [
'name' => 'required|min:3|max:100',
'phone' => 'required',
'date' => 'required',
'address' => 'required|min:3|max:100',
'test' => 'required|min:3|max:100',
], $messages);

Related

Laravel 8: How to send validation response in JSON format using postman

I have this validation, how can I return an error response in postman?
please help guys.
$rules = [
'name' => 'required',
'email' => 'required|email|unique:users',
'password' => 'required|min:6|confirmed',
];
$validator = $this->validate($request, $rules);
$data = $request->all();
use Illuminate\Support\Facades\Validator;
Then write validation like
$validator = Validator::make($request->all(), [
'name' => 'required',
'email' => 'required|email|unique:users',
'password' => 'required|min:6|confirmed',
]);
if ($validator->fails()) {
return response()->json([
'message' => 'Invalid params passed', // the ,message you want to show
'errors' => $validator->errors()
], 422);
}

How can I use fails method validation in controller

controller validator in laravel :
$validationController = $this->validate(request(), [
'title' => 'min:100',
'text' => 'required',
'image' => 'required',
]);
and we can make validator with :
$validationNormaly = Validator::make(request(), [
'title' => 'min:100',
'text' => 'required',
'image' => 'required',
]);
and i can't use $validationController->fails(). how can i use it?
The first validation that you mentioned will fail automatically as designed by the laravel code base.
The Validator::make() i typically use when doing ajax requests and such to the controller method. You will need to run the validation fails method to invoke the failed response like so:
$validator = Validator::make($request->all(), [
'title' => 'required|unique:posts|max:255',
'body' => 'required',
]);
if ($validator->fails()) {
return redirect('post/create')
->withErrors($validator)
->withInput();
}
You Can Use :
$validator = Validator::make($request->all(), [
'title' => 'required|unique:posts|max:255',
'body' => 'required',
])->validate();
take advantage of the automatic redirection with error messages

Laravel: conditional validation rules

In my laravel application I need to apply the validation rules on conditional bases. For example: In the Store method the password field is required and min chars: 6. But, in Update method password field is not required, however, if the user enters the password then it must be greater than 6 chars.
SomeController.php
private function validations($customRules = [])
{
# variables
$rules = [
'contact_person' => 'required|min:2',
'mobile_number' => 'required|numeric',
'pword' => 'required|min:6',
'email' => 'required|email',
'address' => 'required',
'status' => 'required',
];
$messages = [
'contact_person.required' => '`<strong class="style-underline">Contact person</strong>` - Required',
'contact_person.min' => '`<strong class="style-underline">Contact person</strong>` - Must be at least :min chars',
'mobile_number.required' => '`<strong class="style-underline">Mobile number</strong>` - Required',
'mobile_number.numeric' => '`<strong class="style-underline">Mobile number</strong>` - Must be a numeric value',
'email.required' => '`<strong class="style-underline">Eamil</strong>` - Required',
'email.email' => '`<strong class="style-underline">Email</strong>` - Must be a valid email address',
'pword.required' => '`<strong class="style-underline">Password</strong>` - Required',
'pword.min' => '`<strong class="style-underline">Password</strong>` - Must have a at least :min characters',
'status.required' => '`<strong class="style-underline">Status</strong>` - Required',
];
if(!empty($customRules))
$rules = \array_merge($rules, $customRules);
# returning
return request()->validate($rules, $messages);
}
After modifying the rules, based on the update method requirement, the pword field is validated for min chars. Which should not happen as the field was left empty.
Currently I am forced to do this.
public function update()
{
...
# validating submitted data
if(!empty(request()->pword))
$this->validations([ 'pword' => 'min:6' ]);
else
$this->validations([ 'pword' => '' ]);
....
}
You can use nullabe instead required, Blank value converted as null if you are using eloquent, because of below middleware
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
So your method would be like
private function validations($request,$update = false){
$rules = [
'contact_person' => 'required|min:2',
'mobile_number' => 'required|numeric',
'pword' => 'nullable|min:6',
'email' => 'required|email',
'address' => 'required',
'status' => 'required',
];
}

Is there anyway group the errors of multiple form validations in laravel

In the given scenario
request()->validate([
'type' => 'required',
'category' => 'required'
]);
and Again
request()->validate([
'name' => 'required',
'gender' => 'required
]);
Is it possible to get some sort of centralized or complied error that encompasses both the validations?
Then you should use Validator facade to handle this kind of cases.
for ex.
$validator = Validator::make($request->only('type', 'category), [
'type' => 'required',
'category' => 'required'
]);
$validator2 = Validator::make($request->only('name', 'gender'), [
'name' => 'required',
'gender' => 'required'
]);
if ($validator->fails() || $validator2->fails()) {
// return merge $validator->errors() and $validator2->errors();
}

Modify unique attribute validation in Laravel

Trying to customize the error message for unique attribute. Tried changing my validation.php.
$messages = [
'custom' => [
'email' => [
'unique:users' => 'Oops, email is taken. Please try again!'
]
]
],
and I call the validation in controller:
request()->validate([
'email' => 'unique:users',
'password' => 'required|min:3',
]);
And I still get this:
The email has already been taken.
using custom validator
You can create a custom validator and pass your messages into it
$messages = [
'required' => 'The :attribute field is required.',
];
$validator = Validator::make($input, $rules, $messages);
For you this would mean
$messages = [
'email' => [
'unique' => 'Oops, email is taken. Please try again!'
]
];
$rules = [
'email' => 'unique:users',
'password' => 'required|min:3',
];
$validator = Validator::make(request()->all(), $rules, $messages);
if ($validator->fails()) {
return redirect('route/when/failed')
->withErrors($validator)
->withInput();
}
using language file
In resources/lang/{{language}}/validation.php you can add
'custom' => [
'email' => [
'unique' => 'Oops, email is taken. Please try again!',
],
]

Resources