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.

9
  • try put $result = []; Commented Sep 3, 2018 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? Commented Sep 3, 2018 at 21:10
  • I'm sending a FormData with a JSON.stringifyed field. This field contains array. Since it's a JSON PHP considers it as a string so that I'm forced to find workarounds Commented Sep 3, 2018 at 21:13
  • Any particular reason? Why not just send a json request? Commented Sep 3, 2018 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. Commented Sep 3, 2018 at 21:14

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.