Sometimes we may need to write custom validation rules when validating our Eloquent models, in this article I will show you how we can easily make use of the AppServiceProvider class in Laravel to achieve this. The AppServiceProvider takes care of all the bootstrapping for your application, this basically means registering all the components of the application such as service container bindings, event listeners, middleware, and even routes. Service providers are the central place to configure your application.
So how do we write custom validation rules?
Lets say we want to create a validation rule that checks if one field is greater than another. Laravel does not have this rule out-the-box so we need to write our own rule in the boot method of the AppServiceProvider class:
public function boot()
{
Validator::extend('greater_than_field', function($attribute, $value, $parameters, $validator) {
$min_field = $parameters[0];
$data = $validator->getData();
$min_value = $data[$min_field];
return $value > $min_value;
});
}
I have called the validation rule: greater_than_field
Now we can use the validation rule in our Request class like this:
public function rules()
{
return [
'field_1' => 'greater_than_field:field_2',
];
}
As we have added the new validation rule in the AppServiceProvider we don’t need to import anything into our Request class as it will register the rule when the application is first bootstrapped.
Simple as that! We now have our custom validation rule working. It will throw an error if field_1 is not greater than field_2 when the request is made.
To add a custom error message for this rule we can add this into the messages() function of the Request class:
public function messages()
{
return [
'field_1.greater_than_field' => 'Field 1 must be greater than Field 2',
];
}
The benefit of adding this rule in the AppServiceProvider is that it is now globally available to any of your Request objects, so you can validate any of your models with this rule.
Thanks for reading!
Leave a Reply