How To Send Array Of Objects Within Request Body In JSON Format Via Postman?
I want to test my API function by sending array of objects via postman When I send my request in JSON format to the function and then looping through the array to access each object property it gives me the following error: https://i.imgur.com/QV9MDsm.jpg
Here is my request: https://i.imgur.com/4584wf3.jpg
I searched how to send an array of objects using postman and found that I am doing it the right way I selected row under body section so I can add my request body and selected it's format as JSON and added "Content-Type: application/json" to the request header
My API function:
public function createRetailer(Request $request){
$machines = $request->machineInfo;
foreach($machines as $machine){
$newMachine = new Machine;
$newMachine->machine_no = $machine->machineNo;
$newMachine->account_type = $machine->accountType;
$newMachine->machine_type = $machine->machineType;
$newMachine->retialer_id = $retailer->retailerId;
$newMachine->save();
}
}
I expect that i can access each array object properties as a PHP object but I found that it is not an object by testing it using is_object() function:
public function createRetailer(Request $request){
$machines = $request->machineInfo;
foreach($machines as $machine){
return response()->json(is_object($machine));
}
}
I do not know if the problem is within my request or something that I might misunderstand while retrieving data of the request in my controller function
Answer
Either it is an array and in that case, you can call
$object = (object) $machine;
Or it is a string aka JSON, you can call
$object = json_decode($machine);
Or if it is an object/array use
$machine['machineType'];
Also please add a dump of the $machine var
EDIT
Try sending the request not using [] because they will be converted into an array with objects in it, instead, if you remove the [] and only have {} it should only be one object in the request
"machineInfo" : {
"machineNo" : "1123213",
"accountType" : "Paid",
//...rest here..
}
Try this:
public function createRetailer(Request $request){
$machines = $request->machineInfo;
foreach($machines as $machine){
$object = (object) $machine;
return response()->json(is_object($object));
}
}
Related Questions
- → "failed to open stream" error when executing "migrate:make"
- → October CMS Plugin Routes.php not registering
- → OctoberCMS Migrate Table
- → OctoberCMS Rain User plugin not working or redirecting
- → October CMS Custom Mail Layout
- → October CMS - How to correctly route
- → October CMS create a multi select Form field
- → October CMS - Conditionally Load a Different Page
- → How to disable assets combining on development in OctoberCMS
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → OctoberCms component: How to display all ID(items) instead of sorting only one ID?
- → In OctoberCMS how do you find the hint path?
- → How to register middlewares in OctoberCMS plugin?