skip to Main Content

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?

2

Answers


  1. I assume your controller receives data i.e.

    public function functionName(Request $request){
       
            $request->validate([
                'key1' => 'required|integer|min:0',
                'key2' => 'required'
            ]);
    }
    
    Login or Signup to reply.
  2. 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.


    As Tim Lewis correctly mentioned, if all the keys have the same rules, then you can use one single rule and use data.*:

    public function rules()
    {
        return [
            'data' => ['required', 'array'],
            'data.*' => ['required', 'string', 'in:value1,valueN'],
        ];
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search