Laravel custom validation to all model

640 Views Asked by At

I am using laravel latest version and i have a common field in all model called slug.I would to check whether slug is unique or not. i have slug field in all tables

so i have extended Valdiator class

class CustomValidator extends Validator{

protected function validateIsUniqueSlug($attribute, $value, $parameters)
    {

        $isSlugExist= User::where('slug', $value)->exists();
        if ($isSlugExist) {
            return false;
        }
        return true;
    }

}

this works but problem here is i need to repeat this for models but i dont want to do this .is there any better approach so i can handle it in one method

i know laravel has sluggable package but for some reason i cant use that package

1

There are 1 best solutions below

1
Developer On

If you using create cutom rules try this code

php artisan make rule command for create rule go to App\Rules dir u can see passes function condition here

and use any model

'slug'=>[new SlugDomain], in validator 

Rules file

public function passes($attribute, $value)
{
    $isSlugExist= User::where('slug', $value)->exists();
    if ($isSlugExist) {
        return false;
    }
    return true;
}