I’m building an API that takes in an array of ‘additional_data’ but I want some control over the fields that can be passed in.
Take the following JSON:
{
"name": "Joe Bloggs",
"additional_data": {
"type": "example",
"other_type": "example"
}
}
My current validation attempt:
return [
'name' => ['required'],
'additional_data.*' => ['sometimes', Rule::in(['type'])]
];
This always fails validation, what I’m looking for is to validate the key of the array so I can make sure the keys passed in are part of a ‘whitelist’.
3
Answers
What you do now is you try to validate content of
additional_data.type
andadditional_data.other_type
.You can do this by adding a custom validator. For example
and use it inside your current rules
Just specify your whitelist keys using the
array
validation rule:1- In case you want applay same validation on all arrays’ keys you can use the following:
2- In case each key in the array needs different validation use the following: