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

验证请求类中数组数据的country_id与phone联合键唯一性

解决Laravel数组请求中组合字段唯一性验证的错误

问题原因

你的代码报错是因为没有给Rule::unique指定要验证的数据库字段名,Laravel默认会把当前的验证字段名(比如contacts.0.phone)当作users表的数据库字段来查询,而这个字段显然不存在,所以抛出了列未找到的错误。

解决方案

在Rule::unique方法中添加第二个参数,明确指定要验证的数据库字段为phone,然后在where闭包中匹配对应的country_id即可。修改后的代码如下:

foreach(request()->get('contacts') as $contactKey => $contactVal) {
    $rules["contacts.$contactKey.phone"] = [
        'required',
        'string',
        Rule::unique('users', 'phone')
            ->where(fn($query) => $query
                ->where('country_id', $contactVal['country_id'])
            ),
    ];
}

代码说明

  • Rule::unique('users', 'phone'):指定验证users表的phone字段唯一性
  • where闭包:添加额外条件,确保只有当country_id与当前请求的用户country_id匹配时,才检查phone的唯一性,实现phone + country_id的组合唯一性验证

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 07:50:30