Home > database >  How can I validate my request where the data is in a nested structure?
How can I validate my request where the data is in a nested structure?

Time:12-17

My controller receives the following XHR request:

[
  "data" => [
    "key1" => "value1",
    "key2" => "value2",
  ]
]

That's why the validation always returns a fail. But I only want to validate the data within data. Is there a request validation function where I only pass the data?

CodePudding user response:

I assume your controller receives data i.e.

public function functionName(Request $request){
   
        $request->validate([
            'key1' => 'required|integer|min:0',
            'key2' => 'required'
        ]);
}

CodePudding user response:

As a user mentioned in the comments, you have to iterate each entry by using data.KEY format.

If your data is like:

[
    "data" => [
        "key1" => "value1",
        "key2" => "value2",
    ]
]

You can validate it like this:

public function rules()
{
    return [
        'data' => ['required', 'array'],
        'data.key1' => ['required', 'string', 'in:value1,valueN'],
        'data.key2' => ['required', 'string', 'unique:table,column'],
    ];
}

Those rules are just examples, so please, do read How to validate arrays as the documentation has a defined section about it

  • Related