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

Kehet's avatar
Level 2

Http Client Request object

Hi,

Could someone please confirm I'm not missing something really obvious here.

I would like to make post request with built-in http client and if request fails (error 4xx or 5xx) I would like to throw exception with reason phrase, request and response for debugging or further error handling if needed.

However, it seems to be really hard to get request class from \Illuminate\Http\Client\PendingRequest or \Illuminate\Http\Client\Response.

Only way I was able to do it is like this

$request = null;
$response = Http::timeout(5)
                ->beforeSending(function (Request $_request) use (&$request) {
                    $request = $_request;
                })
                ->post('http://example.com/', ['foo' => 'bar']);

dd($request, $response);

and that looks hideous. I could rewrite that as macro PendingRequest::macro(...) but that doesn't remove need of passing variable as reference.

Obviously I could use Guzzle classes to rewrite this, but then I'll lose awesome testing abilities Http class have.

0 likes
2 replies
splatEric's avatar

Do you not have enough information for debug from the Illuminate\Http\Client\RequestException ?

You can call

$response->throw();

to get that for the failures.

eterlinden's avatar

Hey @splateric,

I had run into this issue a while back in. Laravel 8.x, where no matter what I tried with the Http:: facade, specifically on post would return 400 an 500 errors. Turns out that the API, I was posting to for whatever reason could not handle it.

To work around this issue, try using the GuzzleHttp Client instead. (it's in the system)

Here's an example:


$httpClient = new \GuzzleHttp\Client();
$url= 'https://api.whatever.com/v1/something?arg1&arg2;
        $response = $httpClient->request('POST',$url2,
        ['headers' => 
            [
               ....
            ]
        ]);
        $resonseBody = json_decode($response->getBody());
        dd($responseBody);

For any further information about the options you might need, see here: (Guzzle Docs)[https://docs.guzzlephp.org/en/stable/]

Cheers!

Please or to participate in this conversation.