Reputation: 132
'variants' => ['nullable', 'array'],
'variants.*.name' => ['required', 'string'],
'variants.*.options' => ['required', 'array', 'min:1'],
'variants.*.options.*.code' => ['required', 'string', 'distinct'],
I'm having a validation rules above. What I'm trying to achieve is the distinct of the value only for between inner array, but somehow I'm getting an error like this with the input
input:
{
variants: [
{
name: "outer array 1",
options: [
{
code: "A"
},
{
code: "B"
}
]
},
{
name: "outer array 2",
options: [
{
code: "A"
},
]
}
]
}
result:
"error": {
"variants.0.options.0.code": [
"The variants.0.options.0.code field has a duplicate value."
],
"variants.1.options.0.code": [
"The variants.1.options.0.code field has a duplicate value."
]
}
Question: Any way to distinct only between the inner array but not every array?
Upvotes: 3
Views: 1284
Reputation: 1
using custom validation rule:
<?php
namespace App\Rules;
use Illuminate\Contracts\Validation\Rule;
class Distinct implements Rule
{
protected string $message;
protected string $strict = '';
public function __construct(bool $strict)
{
$this->strict = $strict ? ':strict' : '';
}
/**
* @param string $attribute
* @param array $value
* @return bool
*/
public function passes($attribute, $value)
{
try {
$validation = \Validator::make(['array' => $value], [
'array.*' => ["distinct{$this->strict}"]
]);
$this->message = 'The field has a duplicate value.';
return !$validation->fails();
} catch (\Exception $exception) {
$this->message = "array error";
return false;
}
}
public function message()
{
return $this->message;
}
}
Upvotes: 0
Reputation: 320
Not sure if you've already worked it out, but I encountered the same issue and here is my workaround:
$rule = [
...,
'variants.*.options.0.code' => ['required', 'string', 'distinct'],
'variants.*.options.1.code' => ['required', 'string', 'distinct'],
]
If you want to apply 'distinct' rule on each individual item's array elements, you need to specify index specifically. If validating like 'variants.*.options.*.code' => ['required', 'string', 'distinct']
, it will take into account array elements of other items too.
At the moment, I am not figuring out the reason why it behaves like that as when using dd($validator->getRules())
, the rules processed by the validator is the same.
Any additional insight on this would be much appreciated.
Upvotes: 0