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

标签 arrays laravel validation unique

我有一个 API 可以发送一组人员,一些是需要更新的现有对象,一些是需要创建的新对象,它们都需要验证,其中一部分是测试一个独特的电子邮件。我正在使用 FormRequest:

  $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":"carolyn16@example.net",
        "updated_at":"2019-12-05 19:28:59",
        "created_at":"2019-12-05 19:28:59",
        "id":53
    },
    {
        "name":"Person Dave",
        "email":"dave@email.com",
    },
    {
        "name":"Staff Name",
        "email":"staff@email.com",

    }
  ]
}

最佳答案

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

$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]=dd@ddd.dd
staff[2][id]=222
staff[2][email]=eee@eee.ee
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"
]

关于arrays - Laravel 验证唯一更新对象数组失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59197360/

相关文章:

laravel - 如何在laravel中显示除开发人员错误以外的适当错误

javascript - 如果填充了任何相关对象字段,如何使 ng-required 为真?

jquery - 使用 jQuery 1.10.2 在 MVC 4 中进行客户端验证

c - 访问指向字符串的指针数组

javascript - 检查元素是否在数组中两次

java - 访问 JSONArray 中内部数组的值

javascript - Array.apply(null, obj) 的原理是什么?

php - Laravel Many to Many 获取第三个实例选择的集合

php - Laravel 5.2 身份验证和密码路由

asp.net - 如何只验证网页中的某些元素而不验证其他元素?