Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading