【问题标题】:Laravel unique validation in request with other fields WITHIN that request?Laravel 在请求中对请求中的其他字段进行唯一验证?
【发布时间】:2020-11-12 07:21:04
【问题描述】:

`我想针对以下字段进行唯一验证

  • email - 来自Users
  • shop_id - 来自Staff
  • staff_roles 通过字符串数组发送,例如 ["shop_manager", "shop_cleaner"]。如果任何 email/shop_id/role 已经存在,则请求应该无效 - 来自 StaffRoles

如果数据库中存在这些字段的组合,则该请求应被视为无效。

这是我的AddStaffRequest

public function rules()
{
    return [
        'shop_id' => ['required', 'uuid'],
        'email' => ['required', 'email'],
        'staff_roles' => ['array'],
        'staff_roles.*' => ['string'],
    ];
}

有没有简单的解决方案?

【问题讨论】:

    标签: laravel validation request


    【解决方案1】:

    您可以定义一个"after" 验证器:

    /**
     * Configure the validator instance.
     *
     * @param  \Illuminate\Validation\Validator  $validator
     * @return void
     */
    public function withValidator($validator)
    {
        $validator->after(function ($validator) {
            $attributes = $validator->attributes();
            if (StaffRoles::where([
                ['email', $attributes['email']],
                ['shop_id', $attributes['shop_id']],
                ['role', $attributes['role']]])->count() != 0) 
            {
                $validator->errors()->add('constraint_name', 'the combinations already exists');
            }
        });
    }
    

    【讨论】:

    • 天才。谢谢 Berto99。
    【解决方案2】:

    考虑到这是一个稍微复杂一点的逻辑,如何组装一个可以验证请求的查询?

    use Illuminate\Validation\Rule;
    
    Validator::make($data, [
        'email' => [
            'required',
            Rule::exists('staff')->where(function ($query) {
                $query->where('account_id', 1);
            }),
        ],
    ]);
    

    【讨论】:

    • 我强烈反对这种解决方案,因为索引与输入验证无关
    • 是的,我有。但是,我更愿意在请求中捕获它,而不是让它通过控制器、服务一直到数据库以引发异常。这可能吗?
    • 另外它不在同一张桌子上。 email 来自用户,shop_id 来自员工,staff_role 来自员工角色
    • 编辑了答案
    猜你喜欢
    • 2019-11-11
    • 2018-07-05
    • 2021-03-22
    • 2023-03-22
    • 2020-05-02
    • 2015-12-24
    • 2022-09-28
    • 2017-11-17
    • 1970-01-01
    相关资源
    最近更新 更多