Home > other >  CURL Request to Laravel API Returns NULL Values
CURL Request to Laravel API Returns NULL Values

Time:02-10

I am attempting to send an array of objects as part of a JSON request with curl. The request must use json_encode in order to be sent by curl. However I am running into an issue on the Laravel api that is receiving it. Any attempt to get an object from the Request Laravel object returns null ie:

$request->order_number;
$request->items;

This is the case for normal fields and the array of objects I am also sending. The curl appears as

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($request));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
  'Accept: application/json'
));

What is the mistake i am making?

EDIT: To provide more specific information, here is the json_encode var dumped (some omissions): string(694) "{"order_number":"11111","items":"[{"id":"1005","name":"UpRight 011238-004 Washer, Split Lock","sku":"","quantity":1,"price":0.01}]"}"

CodePudding user response:

The solution ended up being rather convoluted:

public function postOrderInformation(Request $data) {
        $request = json_decode(json_encode(json_decode($data->getContent(), true)));
}

This created a useable object from which the data could be extracted from the laravel Requets object. If anyone has a more elegant/less ugly solution, please post it.

  •  Tags:  
  • Related