Home > Enterprise >  Laravel - Array to string conversion issue
Laravel - Array to string conversion issue

Time:07-27

I want to send request via post method with API, and when sending values, sometimes I need to send two values instead of one, and for this I need to loop it. The solution to this is, before sending the request, I save it to the array in the loop and try to complete the process by making json_encode.

My explanation may not be fully explanatory, so I will explain through the codes.

The request I want to throw is normally like this:

CURLOPT_POSTFIELDS =>'
   [
      {
         "items": 
          [
            {
                "name":"string",
                "sku":"string",
            }
          ],
      }
   ]'

But some times the items value needs to have two instead of one. For example:

CURLOPT_POSTFIELDS =>'
   [
      {
         "items": 
          [
             {
                "name":"string",
                "sku":"string",
             },
             {
                "name":"string",
                "sku":"string",
             }
          ],
      }
   ]'

So before i make this request i am saving these values to array in a foreach loop.

$data =array();
foreach ($request->orderItems as $orderItemId) {
   $order_item = OrderItem::where('orderItemId',$orderItemId)->first();
   $data[] = array(
       "sku"=> $order_item->sku,
       "name"=> $order_item->name,
    )
}

And if I'm going to send more than one value, my final code looks like this.

CURLOPT_POSTFIELDS =>'
       [
          {
             "items": '.json_encode($data).',
          }
       ]'

Here is where the problem starts and when i try to send this request i get this error:

Array to string conversion

What should I do exactly? Where am I missing?

CodePudding user response:

You might be missing the Content-Type header for your cURL call.

CURLOPT_HTTPHEADER => [
    'Content-Type' => 'application/json',
],

CodePudding user response:

Try to encode all the content in CURLOPT_POSTFIELDS like this way

 $array = [
        array(
            "name" => "string",
            "sku" => "string",
        ),
        array(
            "name" => "string",
            "sku" => "string",
        )
    ];

    $final = json_encode([["items" => $array]]);

   //now use this variable directly in CURLOPT_POSTFIELDS
   CURLOPT_POSTFIELDS => $final

may it helps ....

  • Related