Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

AtomCoder's avatar

Laravel Http Client - POST Request Issues

Hi Guys,

I'm trying to send a POST request to an api endpoint using Laravel's HTTP client, but I seem to be having issues sending the data.

My request is as follows:

$response = Http::withHeaders([
         'Content-Type' => 'application/json',
         'Accept' => '*/*',
         'Accept-Encoding' => 'gzip, deflate, br',
         'Connection' => 'keep-alive',
   ])->withBasicAuth(env('SEND_USERNAME'), env('SEND_KEY'))->post(env('SEND_URL'), [
      'messages' => [
         'body' => ‘{{ $message }}',
         'to' => ‘{{ $number }}',
         'from' => ‘{{ $site_name }}',
      ]
   ]);

The response I'm receiving is :

{"http_code":400,"response_code":"BAD_REQUEST","response_msg":"The messages array is empty.","data":null}

Just to note, it's saying that the "The messages array is empty" but clearly within my HTTP request above, I have a messages array present.

Can anyone see where I'm going wrong?

0 likes
39 replies
Sinnbeck's avatar

Not sure about the error, but be sure to move the env() variables to a config file and call that instead. This will break as soon as you cache your configuration in production (env() returns null)

Sinnbeck's avatar

Are there any docs for how it should be used, or perhaps a curl example?

AtomCoder's avatar

@Sinnbeck I wasnt going to cache my env? Is there need ?

Documentation for request:

https://developers.clicksend.com/docs/rest/v3/#send-sms

Yes I also have a curl example (that works)

$curl = curl_init();
  curl_setopt_array($curl, array(
  CURLOPT_URL => env('SEND_URL'),
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => '',
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 0,
  CURLOPT_FOLLOWLOCATION => true,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => 'POST',
  CURLOPT_POSTFIELDS =>'{
      "messages": [
          {
                'body': {{ $message }},
                'to': {{ $number }},
                'from': {{ $site_name }},
          }
      ]
    }',
    CURLOPT_HTTPHEADER => array(
      'Content-Type: application/json',
      'Authorization: Basic {{ env('SEND_DETAILS') }}'
    ),
));
Sinnbeck's avatar

@AtomCoder Does this work?

$response = Http::withHeaders([
         'Content-Type' => 'application/json',
         'Accept' => '*/*',
         'Accept-Encoding' => 'gzip, deflate, br',
         'Connection' => 'keep-alive',
   ])
->withBody(json_encode([
      'messages' => [
         'body' => ‘{{ $message }}',
         'to' => ‘{{ $number }}',
         'from' => ‘{{ $site_name }}',
      ]
   ]), 'application/json')
->withBasicAuth(env('SEND_USERNAME'), env('SEND_KEY'))->post(env('SEND_URL'));
Sinnbeck's avatar

And it is up to you if you want to cache config, but I still recommend using laravel properly. Maybe you dont cache now, but in a year you read some article about why you should cache, to speed to your app. So you do, and the app breaks in production

sarunama's avatar

@Sinnbeck i had the same error but different, but also using a ENV() variable.. removing that fixed it for me.. wierd it was working fine until now. i never use cache for the env

Sinnbeck's avatar

@sarunama If you ever run php artisan config:cache or php artisan optimize it will break :)

sarunama's avatar

@Sinnbeck good to know, but i did php artisan optimize:clear, but env was still not working with post method. seem to happen after i composer update

Sinnbeck's avatar

@sarunama Sounds like cache was not cleared properly. But anyways. Not use env() outside of config, is the rule of thumb

AtomCoder's avatar

@Sinnbeck I've tried your code, but I'm getting :

''' json_encode(): Argument #2 ($flags) must be of type int '''

Just in relation to the ENV, I'm using them everywhere to display site name throught the site etc.... Will i need to edit every instance of ENV usage with my entire site ?

1 like
Sinnbeck's avatar

@AtomCoder Oops missed a closing ). Updated the answer

Regarding env, that is completely up to you. But for fun you can try running php artisan optimize and see how much breaks. If its too much work, maybe just add a notice for yourself, to never run that command in production :)

AtomCoder's avatar

@Sinnbeck I have submitted the request but still getting:

{"http_code":400,"response_code":"BAD_REQUEST","response_msg":"The messages array is empty.","data":null}

So annoying lol.

Yes I have ran the config cache before and yes, alot did break lol. But just deleting the cached file resolved the issue.

Sinnbeck's avatar

@AtomCoder Yeah or php artisan optimize:clear, which deletes them as well :)

Strange that that does not work, as it is mentioning the body in their examples.. :/

Sinnbeck's avatar

@AtomCoder How about this?

$response = Http::withHeaders([
         'Accept' => '*/*',
         'Accept-Encoding' => 'gzip, deflate, br',
         'Connection' => 'keep-alive',
   ])
->withBody(json_encode([
      'messages' => [
         'body' => 'foo',
         'to' => 123,
         'from' => 'foobar',
      ]
   ]), 'application/json')
->withBasicAuth(env('SEND_USERNAME'), env('SEND_KEY'))->post(env('SEND_URL'));
Sinnbeck's avatar

Btw. Confused why you are using blade syntax outside of blade? I dont assume this code is inside a blade file? If so, try moving it to a controller method, and just use the variables directly (no {{}})

AtomCoder's avatar

@Sinnbeck I'm not actually using blade syntax there, sorry, I just replaces the data there for demo purposes, I had them hard coded for testing.

AtomCoder's avatar

@Sinnbeck Yea its a weird one this. I've looked at tha package, but I'm trying to avoing using packages where possible. I only need this one api cal to implement a phone verification feature.

But yes I have looked at that previously.

Sinnbeck's avatar

@AtomCoder Sadly it wont let me test it out without a proper key. Otherwise I could give it a shot myself

jorgensolli's avatar

Have you tried Http::asForm()->... I've dealt with APIs in the past that require this. might be a long shot, but worth a try.

jorgensolli's avatar

@AtomCoder What about removing the withHeaders . Everything should be fine left as default. I usually try to strip things down as much as possible in scenarios like these.

I also noticed you've defined fewer headers in the cURL example. So maybe I'm onto something here :D

cardhousemagic's avatar

So I don't know if it is just a side effect of putting the code into this thread, but there seems to be "magic" single quotes in your messages array; the syntax highlighting in the code you posted is messed up because of it...fix that and it might work?

so basically change

[
      'messages' => [
           'body' => ‘{{ $message }}',
           'to' => ‘{{ $number }}',
           'from' => ‘{{ $site_name }}',
      ]
]

to

[
      'messages' => [
           'body' => '{{ $message }}',
           'to' => '{{ $number }}',
           'from' => '{{ $site_name }}',
      ]
]
webrobert's avatar

@AtomCoder

simple post request. this is for click send, yes?

if so, this works just fine...

    return Http::post('https://api-mapper.clicksend.com/http/v2/send.php', [
           'username' => 'youreEmal',
           'key' => 'your key',
           'to' => '61411111111',
           'message' => 'testing send',
       ])->body();

it returns the xml result

AtomCoder's avatar

@webrobert Yes I have used that to send it successfully, but the XML response is not ideal for my situation. The REST API version also returns much more data.

I appreciate your response though.

webrobert's avatar
Level 51

@AtomCoder

ok, this works...

// password is the key...

$sms = Http::withBasicAuth($username, $password)
    ->post('https://rest.clicksend.com/v3/sms/send', [
        'messages' => [
            [
                'to' => '61411111111',
                'body' => 'testing send',
                'source' => 'php'
            ]
        ]
    ])
    ->collect();

dd($sms);

You just needed an additional array wrap!

response...

Illuminate\Support\Collection {#742 ▼ // app/Http/Controllers/TestController.php:82
  #items: array:4 [▼
    "http_code" => 200
    "response_code" => "SUCCESS"
    "response_msg" => "Messages queued for delivery."
    "data" => array:5 [▼
      "total_price" => 0
      "total_count" => 1
      "queued_count" => 1
      "messages" => array:1 [▼
       
	 ...
}

1 like
AtomCoder's avatar

@webrobert Finally!

Fantastic job m8, very much appreceited. A massive thankyou to all in this thread that helped, thanks again guys.

2 likes

Please or to participate in this conversation.