首页 > 解决方案 > Laravel 8 validate unique through columns and rows on create and update

问题描述

I have got 3 columns in my table email_1, email_2, email_3. How to avoid duplicates between the rows while create and update?

For the update method, I can validate by columns like this:

public function rules()
{
    /** OTHER VALIDATION RULES */

    'email_1' => [
    'required',
    'email',
    'unique:users,email_1,' . $this->id,
    ],
    'email_2' => [
    'required',
    'email',
    'unique:users,email_2,' . $this->id,
    ],
    'email_3' => [
    'required',
    'email',
    'unique:users,email_3,' . $this->id,
    ]
    /** OTHER VALIDATION RULES */
}

The problem is avoiding using the same email address on the three input fields of my form?

标签: laravellaravel-8laravel-validation

解决方案


方法一

最简单的方法是使用different验证规则。像这样的东西:

'email_1' => [
  'required',
  'email',
  'different:email_2'
  'different:email_3',
  'unique:users,email,' . $this->id,
],
'email_2' => [
  'required',
  'email',
  'different:email_1'
  'different:email_3',
  'unique:users,email_2,' . $this->id,
],
'email_3' => [
  'required',
  'email',
  'different:email_1'
  'different:email_2',
  'unique:users,email_3,' . $this->id,
],

方法二

我看到您正在Request课堂上进行验证,这很棒,因为您可以使用After Hooks

public function withValidator($validator)
{
    $emails = [Request['email_1'], Request['email_2'], Request['email_3']];
    $validator->after(function ($validator) use ($emails) {
        if (count($emails) == count(array_unique($emails))) {
            // Add error to message bag.
            $validator->errors()->add('key', 'message');
        }
    });
}

上面的示例使用array_unique(),它将删除重复项。比较原始长度与去重长度将显示是否存在重复。


推荐阅读