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.
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.