如何向Laravel Unique Validator添加更多约束

时间:2015-12-24 07:17:18

标签: validation laravel-5

因此,用户需要update个产品和用户的产品必须具有唯一的名称,我不希望用户收到错误消息Product with same name already exists

如何调整Laravel的unique验证器来执行此操作

  $sql = "SELECT `id` FROM `products` WHERE `name` = '$value' AND user_id != '$user_id' AND id != '$id' ";

这将确保如果用户决定保持产品名称不变,则product name with same already exists不会出现任何错误消息,只要它属于同一用户并且产品ID保持不变

我在FormRequest rules()

中尝试了这个
 $id = $this->route('id');
 $user_id = $this->user()->id;

 return [
'name'=>"unique:product,name,user_id,$user_id,id,$id"
 ];

1 个答案:

答案 0 :(得分:1)

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

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

     public function boot()
     {
            Illuminate\Support\Facades\Validator\Validator::resolver(function($translator, $data, $rules, $messages) {
                return new \App\CustomValidation($translator, $data, $rules, $messages);
            });
     }
    
  2. 将CustomValidation.php添加到app文件夹,代码如下

     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
        }
    }
    
  3. FormRequest中的
  4. return [
        'name'=>"custom_unique:$paramter1,$params2,$paramter4"//these paramters will pass to validateCustomUnique function
    ];
    
  5. 从validateCustomUnique函数验证然后返回true或false