Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5 - where to place reusable custom validator?

I'm wondering where is the correct place for custom validator which I want to use on more then one place?

For example, I have min_image_size validator:

Validator::extend('min_image_size', function($attribute, $value, $parameters) {
    $imageSize = getimagesize($value->getPathname());
    return ($imageSize[0] >= $parameters[0] && $imageSize[1] >= $parameters[1]);
});

Where should I place it according right Laravel-way?

like image 273
Limon Monte Avatar asked Apr 20 '15 08:04

Limon Monte


1 Answers

Definitely extend the validator in a Service Provider. You can use the existing app/Providers/AppServiceProvider.php or create another one just for validation.

Then, in the boot() method, add this:

public function boot(){
    $this->app['validator']->extend('min_image_size', function($attribute, $value, $parameters) {
        $imageSize = getimagesize($value->getPathname());
        return ($imageSize[0] >= $parameters[0] && $imageSize[1] >= $parameters[1]);
    });
}

It might also be worth putting the actual validation rules in a separate class and using this syntax:

$this->app['validator']->extend('min_image_size', 'MyCustomValidator@validateMinImageSize');
like image 124
lukasgeiter Avatar answered Oct 13 '22 18:10

lukasgeiter