Laravel 验证对象数组更新时唯一失败

2023-12-12

我有一个 API 发送一组工作人员,有些是需要更新的现有对象,有些是需要创建的新对象,它们都需要进行验证,其中一部分是测试唯一的电子邮件。我正在使用表单请求:

  $rules = [
        'staff.*.name' => 'required|max:128',
        'staff.*.email' => 'required|email|unique:users',
        'staff.*.description' => 'max:512',            
    ];

所以问题是,正如我相信您所看到的,电子邮件地址在更新时未通过唯一验证。这是因为如果 ID 与正在验证的项目相同,则忽略电子邮件的机制给我带来了问题。

我看不到一种方法来获取当前正在验证的对象的 ID,以便我可以访问它的 ID。所以我无法添加以下部分:

'staff.*.email' => 'required|email|unique:users,email,id,' . $currentStaff->id

我看不到太多关于这个具体问题的信息,所以我假设我这样做错了树,或者错过了一些非常明显的东西。

有效负载如下:

{
"staff": [
    {
        "name":"Libbie Turcotte",
        "email":"[email protected]",
        "updated_at":"2019-12-05 19:28:59",
        "created_at":"2019-12-05 19:28:59",
        "id":53
    },
    {
        "name":"Person Dave",
        "email":"[email protected]",
    },
    {
        "name":"Staff Name",
        "email":"[email protected]",

    }
  ]
}

您可以为每个请求人员元素添加规则,循环遍历数组并合并相应的规则:

$rules = [  // this ones are ok for all
    'staff.*.name' => 'required|max:128',
    'staff.*.description' => 'max:512',
];
// here loop through the staff array to add the ignore
foreach($request->staff as $key => $staff) {
    if ( array_key_exists('id', $staff) && $staff['id'] ) { // if have an id, means an update, so add the id to ignore
        $rules = array_merge($rules, ['staff.'.$key.'.email' => 'required|email|unique:users,id,'.$staff['id']]);
    } else {  // just check if the email it's not unique
        $rules = array_merge($rules, ['staff.'.$key.'.email' => 'required|email|unique:users']);
    }
}

那么对于这个请求

staff[1][id]=111
staff[1][email][email protected]
staff[2][id]=222
staff[2][email][email protected]
staff[3][email]=fff@ffff

你将会有这样的规则:

[
    "staff.*.name" => "required|max:128",
    "staff.*.description" => "max:512",
    "staff.1.email": "required|email|unique:users,id,111",
    "staff.2.email": "required|email|unique:users,id,222",
    "staff.3.email": "required|email|unique:users"
]
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Laravel 验证对象数组更新时唯一失败 的相关文章

随机推荐