I need to add validation for a dynamic array whose elements can be strings or subsequent arrays containing strings, but I can’t find a way to save this rule.
My current validation:
$data = $request->validate([
'answers' => ['required', 'array'],
'answers.*' => ['required', 'max:255'],
'answers.*.*' => ['nullable', 'string', 'max:255']
]);
Sample input:
"answers" => array:3 [▼
4 => array:1 [▼
0 => "Tests"
1 => "Tests 2"
]
5 => "Test"
6 => "Yes"
]
3
Answers
Create custom rule class. For ex:
NestedArrayWithStrings
then check:
in a for loop etc.
add to validation like this:
You would need to define a custom rule in Laravel for this.
Run the command
php artisan make:rule NestedArrayWithStrings
and this will create a new file inAppRules
directory.To add this rule, first import the rule class namespace in your controller.
Now, use it in your validator as:
Below will be your recursive code to judge the values and if it passes:
Note: Technically, everything given from the frontend will come as a string, so you will need to add additional checks along with
is_string
to filter out the kind of data you wish to have.So, I created something that might solve your problem, I’ve tried it and works.
First you might want to create a new Rule class, as I commented in your question, maybe using artisan command
php artisan make:rule DynamicArray
for example to give it a name.You’ll need to do something like this inside
app/Rules/DynamicArray
:then in your controller you’ll end with this:
you might debug $data to check if it’s working:
It will pass the valildation:
Hope that solve your problem!