Sandro Antonucci
Sandro Antonucci

Reputation: 1753

How to retrieve all headers sent with Http facade in Laravel?

Based on this https://laravel.com/docs/8.x/http-client you can generate requests via CURL client. There the option to assert specific is sent with Http::assertSent however given a specific request like this

Http::withToken('mytoken')->withHeaders([
    'X-First' => 'foo',
])->post('http://test.com/users', [
    'name' => 'Taylor',
    'role' => 'Developer',
]);

how to get a raw representation of request headers sent to debug it?

Upvotes: 1

Views: 3752

Answers (1)

James
James

Reputation: 16339

The docs for the client outline a way that you can assert a specific header is present, and you can optionally assert the value too; https://laravel.com/docs/8.x/http-client#inspecting-requests.

Sounds like you want to dump out all the headers though.

If we look in the documentation, when you are asserting a request was sent, you are passed an instance of Illuminate\Http\Client\Request. If we take a look at Illuminate\Http\Client\Request there is a public method for getting all the headers:

/**
 * Get the request headers.
 *
 * @return array
 */
public function headers()
{
    return collect($this->request->getHeaders())->mapWithKeys(function ($values, $header) {
        return [$header => $values];
    })->all();
}

So in your test, you could do something like this:

Http::fake();

//... your test

Http::assertSent(function ($request) {
    dump($request->headers());

    // replace this with an actual assertion but it’s needed to print the dump out
    return true;
});

Upvotes: 3

Related Questions