my api receive single array of object from client side like following:
[
{
"datetime": "2022-07-19 12:04:03",
"receiptNumber" : "4010",
"isRefund": 0,
"amount" : 1025
},
]
and whem try to validate request at api side checked success and process to database success my issue happen when try to sent multi object inside array like following :
[
{
"datetime": "2022-07-19 12:04:03",
"receiptNumber" : "4010",
"isRefund": 0,
"amount" : 1025
},
{
"datetime": "2022-07-19 12:04:03",
"receiptNumber" : "4009",
"isRefund": 0,
"amount" : 1025
}
]
when i am try to validate first object inside array using foreach like following :
$array = $request->all();
foreach($array as $sdsa){
$this->validate($sdsa, [
'datetime' => 'required|date_format:Y-m-d H:i:s',
'amount' => 'required|numeric',
'isRefund' => 'required|integer|between:0,1',
'receiptNumber' => 'required|string',
]);
}
in this case api return error :
"message": "Argument 1 passed to App\\Http\\Controllers\\Controller::validate() must be an instance of Illuminate\\Http\\Request, array given,
so that i am asking how can convert this format:
array:4 [
"datetime" => "2022-07-19 12:04:03"
"receiptNumber" => "4010"
"isRefund" => 0
"amount" => 1025
]
to
{
array:4 [
"datetime" => "2022-07-19 12:04:03"
"receiptNumber" => "4010"
"isRefund" => 0
"amount" => 1025
]
}
CodePudding user response:
You can use 'json_encode()'.
Example;
$myArray = array("datetime" => "2022-07-19 12:04:03", "receiptNumber" => "4010", "isRefund" => 0, "amount" => 1025);
Output;
[
"datetime" => "2022-07-19 12:04:03",
"receiptNumber" => "4010",
"isRefund" => 0,
"amount" => 1025,
]
Than if you use json_encode like this;
$myArray = json_encode($myArray);
Output;
{
[
"datetime" => "2022-07-19 12:04:03",
"receiptNumber" => "4010",
"isRefund" => 0,
"amount" => 1025,
]
}
CodePudding user response:
You need to use
Validator::make($sdsa, [
'datetime' => 'required|date_format:Y-m-d H:i:s',
'amount' => 'required|numeric',
'isRefund' => 'required|integer|between:0,1',
'receiptNumber' => 'required|string',
])->validate()