How would you validate individual array elements, for example, using the Distinct rule? #222
-
Given an array, I want to ensure it only contains distinct values. Using regular Laravel validation rules, I can define the validation as the following. Even though slightly confusing (I would expect I can assign the Validator::make([
'tags' => ['foo', 'foo', 'bar']
], [
'tags' => 'array',
'tags.*' => 'distinct',
])->errors();
// this results in something like:
[
"tags.0" => [
"The tags.0 field has a duplicate value.",
],
"tags.1" => [
"The tags.1 field has a duplicate value.",
],
] How can I replicate the same using a Data Object and validation attributes? FWIW, the following does not work: class MyData extends Data
{
public function __construct(
#[Distinct]
public array $tags,
) {
}
} |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
At the moment the best solution is to manually add the distinct rule using a static |
Beta Was this translation helpful? Give feedback.
At the moment the best solution is to manually add the distinct rule using a static
rules
method. Our current architecture doesn't supporting adding rules like'tags.*' => 'distinct'
. I'm taking a look into how we can change this but it will be quite a bit of work.