且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何向Laravel唯一验证器添加更多约束

更新时间:2022-11-27 18:14:50

您应该添加自定义验证,这是我的解决方案:

You should add a custom validation, here is my solution:

  1. 在App \ Providers \ AppServiceProvider类中,像这样更改启动功能

  1. in class App\Providers\AppServiceProvider,change the boot function like this

 public function boot()
 {
        Illuminate\Support\Facades\Validator\Validator::resolver(function($translator, $data, $rules, $messages) {
            return new \App\CustomValidation($translator, $data, $rules, $messages);
        });
 }

  • 将CustomValidation.php添加到应用程序文件夹中,代码如下

  • add CustomValidation.php to app folder,code like this

     use Illuminate\Validation\Validator;
     class CustomValidation extends Validator
     {
    
        public function validateCustomUnique($attribute, $value, $parameters)
        {
              //$attribute is the filed name which you want validate
              //$value is the value of that filed
              //$parameters is an array which you can pass extra paramter form validation
        }
    }
    

  • 在FormRequest中

  • in FormRequest

    return [
        'name'=>"custom_unique:$paramter1,$params2,$paramter4"//these paramters will pass to validateCustomUnique function
    ];
    

  • 您是否通过validateCustomUnique函数进行验证,然后返回true或false