lundi 1 août 2016

Passing json parameter in request and validating it using the Laravel Request

I want to pass a json string as a request parameter to my Laravel 5 app with other paramters such as name, token and want it to be validated using Laravel FormRequest. My json object looks like so :

[
    {
        "name": "Test 1",
        "type": "radio",
        "cost": 500
    },
    {
        "name": "Test 2",
        "type": "radio",
        "cost": 50
    },
    {
        "name": "Test 3",
        "type": "radio",
        "cost": 5
    }
]

I'm trying to validate it as follows in my FormRequest class :

$test = \GuzzleHttp\json_decode($this->simple_json);
for ($i = 0; $i < count( $test ); $i++) {
            $rules["simple_json.{$i}.name"] = 'required|string';
            $rules["simple_json.{$i}.type"] = 'required|string';
            $rules["simple_json.{$i}.cost"] = 'required|integer';
}

It looks like so in POSTMAN enter image description here

But I keep getting

"simple_json.0.name": [
      "The simple json.1.name field is required."
    ],
"simple_json.0.cost": [
      "The simple json.1.cost field is required."
    ],
"simple_json.0.type": [
      "The simple json.1.cost field is required."
    ],
"simple_json.1.name": [
      "The simple json.1.name field is required."
    ],
"simple_json.1.cost": [
      "The simple json.1.cost field is required."
    ],
"simple_json.1.type": [
      "The simple json.1.cost field is required."
    ],
"simple_json.2.name": [
      "The simple json.1.name field is required."
    ],
"simple_json.2.cost": [
      "The simple json.1.cost field is required."
    ],
"simple_json.2.type": [
      "The simple json.1.cost field is required."
    ]

Is there some problem with the way I'm sending the parameter or the handling part? How to handle such nested json request validation?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire