jeudi 14 septembre 2017

Laravel validate array of object json

I have a POST endpoint on my Laravel 5.5 API, I used postman to test my route and here is the problem. I want to send an array of the same kind of object, like this :

[
  { 
   "name":"test",
   "tag":"TEST"
  },
  {
   "name":"test2",
   "tag":"TEST_2"
  }
]

But I can't manage to validate it properly.

in my controller, I have this :

$validator = Validator::make($requests->all(), [

   'name' => 'required|string',
   'tag' => 'required|string'
]);

if($validator->fails()) 
   //Warn user for errors 

I also tried with the simple

$this->validate($requests->all() .... )

I tried renaming the rules with '.name' and '*.name' but no success.

I tried replacing $request->all() with $request->input()but no success.

I also tried to loop over it but I get exceptions

foreach($request as $req){

  $validator = Validator::make($req ....) 

  //rest of the code
}

On the other hand, I can retrieve the data like this $datas = $request->all() and store them but there is no validation.

The only solution that seems to be working is naming my array :

{
 "data" : [
      { 
       "name":"test",
       "tag":"TEST"
      },
      {
       "name":"test2",
       "tag":"TEST_2"
      }
    ]
}

And then name the rules with 'data.*.name' but this obliges the API user to parse the array. Let suppose I have an array $array wich I want to store, I need to do

$arrayParsed = ['data' => $array]

and call the API with $arrayParsed, which I think is a little redundant.

Is there a better way to handle the problem?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire