[英]Validate composite key within array?
For validating phone numbers in my application I need to combine it with a country id to make sure the combination is unique not the phone number itself.为了在我的应用程序中验证电话号码,我需要将它与国家 ID 结合起来,以确保组合是唯一的,而不是电话号码本身。 This has not been a problem in the past and has been solved using the following method in validation classes
这在过去不是问题,已经在验证类中使用以下方法解决了
'phone' => ['required', 'string',
Rule::unique('users')
->where('country_id', $this->country_id)
->where('phone', $this->phone)
],
However I am now accepting an arrray of users and the following rule does not seem to work但是我现在接受了一系列用户并且以下规则似乎不起作用
'contacts.*.phone' => ['required', 'string',
Rule::unique('users')
->where('country_id', $this->country_id)
->where('phone', $this->phone)
],
Have not found anything on stack overflow or within the documentation for this problem尚未在堆栈溢出或文档中找到任何有关此问题的信息
You can achieve this using Rule::forEach
, in your use case it might look like the following:您可以使用
Rule::forEach
实现此目的,在您的用例中它可能如下所示:
'contacts.*.phone' => [
'required',
'string',
Rule::forEach(function ($value, $attribute) {
return [
Rule::unique('users')
->where('country_id', $value)
->where('phone', $value),
];
}),
],
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.