Search code examples
phplaravelframeworks

Laravel $request->validated() for data that has object datatype inside the request body


I have used $request->validated() to validate request body that only consists of normal key-value pair, but what if the request body has an object inside it?

Example:

// this works just fine
{
    "key1": "value1",
    "key2": "value2"
}

the return of $request->validated() will be only for key1 and key2, but when it comes to body like this:

{
    "key1": "value1",
    "object1": {
        "key2.1": "value2.2"
        "key2.2": "value2.2"
     }
}

and when I tried to create object1 record using:

object1::create($request->validated())

it throwed an error because the $request->validated() only validate any normal key-value data and did not dive into the object's property. Any idea to this? Thanks in advance.


Solution

  • Turns out you can use request->validated()["object"] to get validated object inside request body, so you don't need to validate every key inside that object anymore.