Reputation: 4180
I have a JSON structure like this which I want to validate.
{
"result":[{
"product_id": 1,
"client": 49,
"ticket": 2,
"sold_from_date": 1431588871,
"sold_to_date": 1433122200,
"discount_given":18,
"cheques":[{
"cheque_number" : 123456,
"amount": 6000,
"cheque_date": 1433122200,
"bank": "UCD"
},
{"cheque_number" : 456234,
"amount": 6000,
"cheque_date": 1433122200,
"bank": "AMB"
}
]
},
{
"product_id": 1,
"client": 49,
"ticket": 2,
"sold_from_date": 1433122200,
"sold_to_date": 1434688959
}]
}
I want to validate this JSON in Laravel.
I tried doing this:
$validator = \Validator::make($data, []);
$validator->each('result.product_id' , ['required|numeric']);
$validator->each('result.sold_from_date' , ['required|numeric']);
$validator->each('result.sold_to_date' , ['required|numeric']);
$validator->each('result.cheques.cheque_number' , ['sometimes|required|numeric']);
$validator->each('result.cheques.amount', ['sometimes|required|numeric']);
return $validator;
I am getting this error every time:
Attribute for each() must be an array.
Also, how can I validate cheques? Because it can or cannot be in JSON.
Upvotes: 2
Views: 5888
Reputation: 8340
Create an array
from json
with json_decode
function.
Try:
$dataarray = json_decode($data);
$validator = \Validator::make($dataarray['result'][0], [
'product_id' => 'required|numeric',
'sold_from_date' => 'required|numeric'
]);
iterate the array:
$roles = array(
'product_id' => 'required|numeric',
'sold_from_date' => 'required|numeric'
);
foreach($data as $element)
{
foreach($element as $value) {
$validator = \Validator::make($value, $roles);
}
}
Upvotes: 1