Laravel 检查多个字段的唯一验证

Laravel Unique validation on checking multiple fields

我有 subject 个表,字段是 standard_idstream_idmedium_idboard_idsubject_name 等等。

我想为 subject_name 添加唯一规则,该规则对于 standard_idstream_idmedium_idboard_id 字段是唯一的。

$validator = Validator::make( $inputs, 
            [
                'v_name' => [
                        'required',
                        Rule::unique( 'tbl_subject' )->ignore( $id, 'id' ),
                    ],
            ],
            [
                'v_name.required' => 'Name is required',
                'unique' => 'Name address already exits.',
            ]
        );

例子

standard_id, stream_id, medium_id, board_id subject_name

1             2            1            3          A
3             2            4            1          B
1             3            1            4          c

验证就像 subject_name “A”对于 1、2、1、3 是唯一的。B 对于 3、2、4、1 是唯一的。 但是 subject_name "A" 对于 2,2,1,3 等不是唯一的..

*** 与 OP 讨论后 ***

问题应该说明他们正在尝试插入一条记录,并希望验证数据库的唯一性。一种方法是通过 custom rule,像这样:

class UniqueSubject implements Rule
{
    private $keys;

    public function __construct(array $keys) {
        $this->keys = $keys;
    }

    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        return ! Subject::where($this->keys)->where('subject_name', $value)->exists();
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return 'The Subject Name must be unique for the given standard, stream, medium and board.';
    }
}

然后您可以在您的规则中使用验证,例如:

$keys = $request->only('i_standard_id', 'i_stream_id', 'i_board_id', 'i_medium_id');

$validator = Validator::make( $inputs, [
    ...
    'subject_name' => [
        'required',
        'string',
        new UniqueSubject($keys)
    ],
    ...
]);