如何向Laravel唯一验证器添加更多约束 [英] How to add more constraints to Laravel Unique Validator

查看:213
本文介绍了如何向Laravel唯一验证器添加更多约束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

So a user needs to update products and user's products must have unique names and I don't want the user to receive the error message Product with same name already exists

我如何调整Laravel的unique验证器来做到这一点

How do I tweak the Laravel's unique validator to do this

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

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

This will ensure that if user decides to leave product name unchanged, there will not be any error message for product name with same already exists as long as it belongs to the same user and the product id remains same

我已经在FormRequest Rules()中尝试过此操作

I have tried this in FormRequest rules()

 $id = $this->route('id');
 $user_id = $this->user()->id;

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

推荐答案

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

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
  • 这篇关于如何向Laravel唯一验证器添加更多约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆