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"
]
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 DynamicArrayfor 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!