You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel 9中FormRequest实现多字段组合唯一性验证问题

问题原因与解决方案

你的验证规则失效的核心原因是**Rule::unique()方法的第一个参数传错了**:你传入的是字段名email,但该方法要求传入的是数据表名称email_updates。

修正后的验证规则代码如下:

public function rules()
{
    return [
        'email' => [
            'required|email:rfc,dns|min:5|max:75',
            Rule::unique('email_updates')->where(function ($query) {
                $query->where('product_uuid', $this->product_uuid)
                    ->where('affiliate_uuid', $this->affiliate_uuid);
            })
        ],
    ];
}

补充说明:

  • Rule::unique($tableName)的第一个参数必须是对应的数据表名,Laravel会基于这个表构建唯一性查询逻辑。
  • 链式调用的where方法用来添加额外匹配条件,确保email+product_uuid+affiliate_uuid三者组合唯一,这部分你的逻辑是正确的。
  • 如果后续涉及更新操作(需要排除当前记录本身避免误判重复),可以在unique方法后追加ignore($id),比如:Rule::unique('email_updates')->ignore($this->route('email_update'))->where(...)。

内容的提问来源于stack exchange,提问作者wruckie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 19:35:30