简体   繁体   中英

Laravel custom validation to all model

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

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM