Reputation: 125
In laravel 8 how can use the validation to check the file name provided in the array were unique.
` "main": [
{
"content": "ABC",
"filename": "recording_1",
"code": "264",
"parameters": ""
},
{
"content": "XYZ",
"filename": "recording_2",
"code": "264",
"parameters": ""
}
...more to come
]`
Above is the request structure. From that request, I have to check the all filename should be unique How can I achieve this?
Upvotes: 0
Views: 230
Reputation: 15319
you can use distinct
$validator = Validator::make(
[
'main' =>
[
[
"content" => "ABC",
"filename" => "recording_1",
"code" => "264",
"parameters" => ""
],
[
"content" => "XYZ",
"filename" => "recording_1",
"code" => "264",
"parameters" => ""
]
]
],
['main.*.filename' => 'distinct']
);
then you can check
if($validator->fails()){
echo "<pre>";
print_r($validator->errors());
exit();
}
Output will be
Illuminate\Support\MessageBag Object
(
[messages:protected] => Array
(
[main.0.filename] => Array
(
[0] => The main.0.filename field has a duplicate value.
)
[main.1.filename] => Array
(
[0] => The main.1.filename field has a duplicate value.
)
)
[format:protected] => :message
)
Ref:https://laravel.com/docs/8.x/validation#rule-distinct
Upvotes: 1