skip to Main Content

I’m working with Laravel and trying to send a PUT request to an API with the following code:

$client->put('api_nginx/v1/countries/' . $id . '/update', [
    'json' => $request->all(),
]);

The data being sent in the request ($request->all()) is as follows:

{
  "country_iso2": [
    "US",
    "NL"
  ],
  "url": [
    "https://example.com",
    "https://example.com"
  ],
  "wager": [
    null,
    null
  ],
  "minimum_withdrawal_time": [
    null,
    null
  ],
  "maximum_withdrawal_time": [
    null,
    null
  ],
  "payment_type_ids": [
    [
      "1",
      "3",
      "4"
    ],
    [
      "1",
      "2",
      "4",
      "5"
    ]
  ]
}

However, I am facing an issue where the payment_type_ids field is not being sent when the request is made. I believe the issue is due to the payment_type_ids being a multi-dimensional array. Interestingly, the request works perfectly when I use Postman.

Could someone please help explain why the multi-dimensional array is causing issues with the Laravel HTTP client and how I can fix it?

2

Answers


  1. The problem happens because the Laravel HTTP client (Http::put) automatically converts the data you send into JSON format. When you include a multi-dimensional array like payment_type_ids, Laravel relies on PHP’s json_encode() function to handle the conversion.

    To ensure that the data is properly formatted and sent as expected, explicitly encode the data as JSON and specify the Content-Type header

    $client->put('api_nginx/v1/countries/' . $id . '/update', [
        'headers' => [
            'Content-Type' => 'application/json',
        ],
        'body' => json_encode($request->all()),
    ]);
    

    Points to take away

    1. Explicit Encoding: Use json_encode() to ensure the nested arrays are encoded correctly.
    2. Headers: Set the Content-Type header to application/json to inform the server about the data format.
    3. Body Parameter: Pass the JSON-encoded data as the body parameter instead of json. Using json automatically encodes the data, but explicit encoding with body gives you more control.
    Login or Signup to reply.
  2. You need to encode the request parameter for Laravel to be able to handle it correctly. Also, send the request as a body not json

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search