我想访问嵌套验证数组中的信息以进行自定义验证,这是我的代码:
return [
...,
'amount' => ['nullable', 'numeric'],
'currency_id' => ['nullable', 'integer', Rule::in($allowedCurrencyIds)],
'details' => ['nullable'],
'details.*.product_id' => ['required', 'integer', 'exists:products,id'],
'details.*.product_collection_id' => [
'nullable',
'integer',
'exists:product_collections,id',
new ProductAndCollectionValidator($this->details.*.->product_id, $this->details->product_collection_id)
],
...
]
如您所见,我想访问产品 ID 和产品集合 ID 以及详细信息*,以发送到自定义验证器 ProductAndCollectionValidator。我需要考虑到product_collection_id有时可能为空。这是第一步。
第二步我想确保详细信息数组中没有重复的product_id和product_collection_id
我该怎么做?
您可以使用 Laravel 的自定义验证规则和验证闭包。在您的验证器上尝试一下:
return [
// Other validation rules...
'details.*.product_id' => ['required', 'integer', 'exists:products,id'],
'details.*.product_collection_id' => [
'nullable',
'integer',
'exists:product_collections,id',
function ($attribute, $value, $fail) {
// Accessing nested values within details array
$productId = $this->input('details')[$this->getIndexFromAttribute($attribute)]['product_id'];
// Custom validation logic using ProductAndCollectionValidator
$validator = new ProductAndCollectionValidator($productId, $value);
if (!$validator->passes()) {
$fail($validator->message());
}
}
],
'details' => ['nullable', function ($attribute, $value, $fail) {
// Custom validation rule to check for duplicates
$uniqueDetails = collect($value)->unique(function ($detail) {
return $detail['product_id'] . '-' . $detail['product_collection_id'];
});
if ($uniqueDetails->count() !== count($value)) {
$fail('Duplicate product_id and product_collection_id combinations found.');
}
}],
];
function getIndexFromAttribute($attribute)
{
return explode('.', str_replace(['[*]', '*'], ['.', ''], $attribute))[1];
}
让我知道。干杯。