1

I have a request in which I pass an array of JSON objects. It has the following structure

[ {path: 'string', class: 'string'} ]

As far as I understand there is no easy way to check this array so I've tried next

$validatedData = $request->validated();

        $result = ['data' => []];
        foreach ($validatedData['items'] as $item) {
            $result['data'][] = json_decode($item);
        }

        Validator::make($result, [
            'data.*.path' => 'required|url',
            'data.*.class' => 'required|string'
        ])->validate();

However it results in

array(1) {
  ["data"]=>
  array(2) {
    [0]=>
    object(stdClass)#813 (2) {
      ["link"]=>
      NULL
      ["class"]=>
      NULL
    }
    [1]=>
    object(stdClass)#814 (2) {
      ["link"]=>
      NULL
      ["class"]=>
      NULL
    }
  }
}

Somehow a validator cuts off the data. When I try without Validator::make part it works fine, however I need to control what I retrieve.

Sergey
  • 7,184
  • 13
  • 42
  • 85
  • try put `$result = [];` – Alexander Villalobos Sep 03 '18 at 21:10
  • Why wouldn't you be able to validate the JSON input? I'm a bit confused on your problem and why you'd have to decode the JSON and build a result array to begin with. Are you sending JSON in a non-json request? – Devon Bessemer Sep 03 '18 at 21:10
  • I'm sending a FormData with a `JSON.stringify`ed field. This field contains array. Since it's a JSON PHP considers it as a string so that I'm forced to find workarounds – Sergey Sep 03 '18 at 21:13
  • Any particular reason? Why not just send a json request? – Devon Bessemer Sep 03 '18 at 21:14
  • 1
    You have an array of objects since json_decode returns an object. For it to return an associative array, you need to do `json_decode($item, true)`. Try it and see if that works. – José A. Zapata Sep 03 '18 at 21:14
  • Because I *need* to send a FormData. It contains a file. – Sergey Sep 03 '18 at 21:14
  • @JoséA.Zapata well.. That worked somehow. However I'm curious why it didn't work with an array of objects – Sergey Sep 03 '18 at 21:17
  • Seems reasonable since stdclass objects would never exist in a request. – Devon Bessemer Sep 03 '18 at 21:18
  • @JoséA.Zapata please post your answer I'll mark it. If possible please expand your explanation for those who new and got stuck with the same problem. – Sergey Sep 03 '18 at 21:20

1 Answers1

4

You have an array of objects, since json_decode returns an object. For it to return an associative array, you need to do json_decode($item, true). You need to do that because the Laravel validator need both the data and the validation rules to be arrays. Since you were passing an array of objects, it didn't work.

José A. Zapata
  • 1,187
  • 1
  • 6
  • 12