简体   繁体   English

Laravel对所有模型的自定义验证

[英]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. 我正在使用laravel最新版本,并且在所有模型中都有一个共同的领域称为slug 。我将检查slug是否唯一。 i have slug field in all tables 我在所有表中都有子弹字段

so i have extended Valdiator class 所以我延长了Valdiator课

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 我知道laravel的包装不好,但由于某种原因我无法使用该包装

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 php artisan make rule命令创建规则转到App \\ Rules目录,您可以在此处看到通过功能条件

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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