【问题标题】:Laravel validation for two column with same value exist on table表上存在具有相同值的两列的 Laravel 验证
【发布时间】:2020-01-21 13:44:51
【问题描述】:

实际情况是我必须检查表上是否存在两个相同的列值 例如首先我输入user_id = 1rv_id = 2

我不应该再次存储相同的序列值(user_id = 1 and rv_id = 2) 但我可以存储user_id = 1 and rv_id = 3user_id =1 and rv_id =1

$request->validate([

            'rv_id'     => 'required|unique:favorite_unites,rv_id,user_id|exists:rvs,id', 
            'user_id'   => 'required|unique:favorite_unites,user_id,rv_id|exists:users,id',

        ]);

【问题讨论】:

    标签: laravel validation


    【解决方案1】:

    在这种情况下,我猜你需要创建一个自定义规则

    请求类:

    // Read more in bottom
    'name' => ['required', new MustMatchCustomValue('rv_id')],
    

    规则类(使用工匠创建)

    class ValidateTwoValues implements Rule
    {
        protected $rvId;
    
        public function __construct($rvId)
        {
            $this->rvId = $rvId;
        }
    
        /**
         * Determine if the validation rule passes.
         *
         * @param  string  $attribute
         * @param  mixed  $value
         * @return bool
         */
        public function passes($attribute, $value)
        {
            // $value contains the user_id
            // $this->rvId contains the other value
            // Do DB check here using DB::table('')...etc
    
            // return true if it's okay, or false if not
        }
    
        /**
         * Get the validation error message.
         *
         * @return string
         */
        public function message()
        {
            return 'You already have the selected RV.';
        }
    }
    

    注意:我注意是否将属性字符串作为参数传递给 Rule 类实际上会发送值或只是字符串,如果它只是一个字符串,你必须交换它new MustMatchCustomValue($this->rv_id)

    【讨论】:

      【解决方案2】:

      你实际上是在正确的轨道上,你只是犯了一个简单的错误。将exists:rvs,id 更改为exists:rvs 并将exists:users,id 更改为exists:users(如果这些是您的表名)。您需要在该验证规则中传递 table_name 而不是 column。来自官方文档:

      存在:表、列

      正在验证的字段必须存在于给定的数据库表中。

      阅读有关验证的更多信息here

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-11-10
        • 2019-11-15
        • 2021-12-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-07-09
        相关资源
        最近更新 更多