isaackearl's avatar

Nested Json Validation... for dynamic number of items

So I'm wondering if there is any way to handle validation for a nested set of json objects with multiple values... for example my json could look like this:

{"mentions": [
    {"id":1, "name":"keeling"},
    {"id":2, "name":"numero2"},
] }

but since this is an array of multiple responses... this doens't work

'mentions.id' => 'required',

the only way I can get this to work is by doing this:

'mentions.0.id' => 'required',
'mentions.1.id' => 'required',

the number of items could be dynamic however and I am looking for a way to apply validation rules on all values...

Any ideas?

Thanks, Isaac

0 likes
4 replies
isaackearl's avatar

btw @JeffreyWay when I try and edit my post above I get the "Woops something went wrong..." error page.

kfirba's avatar
kfirba
Best Answer
Level 50

@isaackearl I know it's not a perfect solution, but one way to tackle this would be to add as many validation rules as needed. For example:

$mentions = json_decode($json, true);

for ($ = 0; $i < count($mentions); $i++) {
    $rules["mentions.{$i}.id"] = 'required' 
}

I would like to see the full workflow to maybe be able to suggest a better solution.. where do you get the json form? how do you parse it? etc.

Shahrukh4's avatar

You can provide the validation in inner array element just by putting star(*) and giving the key you want the validation on e.g.(put star symbol in place of my 'star' keyword)

      Validator::make($data, [
            'goals.(star).goal'      => 'required|min:5' ,
            'goals.(star).amount'    => 'required|integer|min:1'
       ]);
4 likes

Please or to participate in this conversation.