【问题标题】:Laravel validation unique on two columnsLaravel 验证在两列上是唯一的
【发布时间】:2020-04-18 10:45:13
【问题描述】:

下面是我的表结构:

公司

  • 身份证
  • uuid
  • 公司名称

corp_branches

  • 身份证
  • corp_id
  • 分支名称

关系定义为每个公司可以有许多 corp_branches,但我想检查每个公司下的 branch_name 是否应该是唯一的。不同公司下的两个不同分支机构可以同名,但一个公司下的两个分支机构不能同名。

我试过了

'branch_name' => 'required|string|max:100|unique:corp_branches,branch_name,NULL,id,corp_id,'.$this->get('corp_id'),

【问题讨论】:

  • 您是否也会使用这些规则来更新分支名称?
  • 不,我会单独写一篇进行编辑。这些仅用于创作。
  • 您能否解释一下您目前的验证是如何不起作用的,即哪些不起作用而应该起作用,以及您收到的错误消息(如果有的话)。
  • 两列唯一?只有branch_name
  • @rwd 它没有给出任何错误,但它允许我在一个公司下拥有相同的分支机构名称

标签: php laravel validation laravel-6


【解决方案1】:

你需要Custom Validation Rules

步骤 #1 - 生成规则

php artisan make:rule UniqueBranch

步骤 #2 - 修改 app/Rules/UniqueBranch.php

<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;

class UniqueBranch implements Rule
{
    protected $corp_id;

    /**
     * Create a new rule instance.
     *
     * @return void
     */
    public function __construct($corp_id)
    {
        $this->corp_id = $corp_id;
    }

    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        // Assume your model name is `Corporation`
        $corporation = Corporation::find($this->corp_id);

        if ($corporation) {
            $exists = $corporation
                ->corp_branches() // assume you have relation to braches
                ->where('name', $value)
                ->count();

            if (!$exists) {
                return true;
            }
        }

        return false;
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return 'The branch name has already been taken.';
    }
}

步骤#3 - 使用UniqueBranch

'branch_name' => [
    'required',
    'string',
    'max:100',
    new UniqueBranch($this->get('corp_id'))
]

【讨论】:

  • 我们不能在不创建任何新规则的情况下做到这一点。
【解决方案2】:
'branch_name' =>['required', 'unique:corp_branches,corp_id,'.$this->id.',NULL,corp_id,branch_name,'.$request->input('branch_name')]

【讨论】:

  • 能否详细说明异常情况
  • 首先它为 udefined 变量 '$request' "message": "Undefined variable: request", "exception": "ErrorException" 抛出异常,所以我将 $request 更改为 $this,仍然它抛出以下异常“消息”:“未定义偏移量:3”,“异常”:“ErrorException”,“文件”:“/var/www/mydomain/vendor/laravel/framework/src/Illuminate/Validation/Concerns/ ValidatesAttributes.php", "line": 863
猜你喜欢
  • 1970-01-01
  • 2021-04-28
  • 2013-08-30
  • 1970-01-01
  • 2022-01-25
  • 2020-04-30
  • 2020-08-01
  • 2012-10-10
  • 2014-08-08
相关资源
最近更新 更多