Skip to content
Advertisement

Laravel CURL – Passing a string to HTTP URL (Postfields)

I use Laravel 9 and the built-in method Http::withHeaders ($headers)->post($url, $data).

In the $data variable, I pass the string that resulted from http_build_request with the “&” separator. But Laravel tries to make an array out of it and send data.

The API service returns me an error. Please tell me how you can force Laravel to pass exactly a STRING(!), and not an array?

My code:

$array = [
            'key1' => 'value1',
            'key2' => 'value2',
            // etc...
];
$headers = [
            'Content-Type' => 'application/x-www-form-urlencoded',
            'HMAC' => $hmac
];

$data = http_build_query($array, '', '&');
$response = Http::withHeaders($headers)->post($api_url, $data);
return json_decode($response->getBody()));

Advertisement

Answer

Have you tried, asForm?

$response = Http::withHeaders($headers)->asForm()->post($api_url, $data);

If you would like to send data using the application/x-www-form-urlencoded content type, you should call the asForm method before making your request.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement