travis.elkins
2 months ago
123
2
Laravel

How to reuse Laravel 7's new HTTP client...

Posted 2 months ago by travis.elkins

Anyone know how to reuse Laravel 7's new HTTP client or does it need to be "configured" for every use...?

For example, if one writes something like this:

$response = Http::baseUrl('https://some.base.address.com')
    ->acceptJson()
    ->asJson()
    ->withToken($token)
    ->get('users');

And then later on or elsewhere in the code you want to hit the same API, but to get/do something else:

$response = Http::baseUrl('https://some.base.address.com')
    ->acceptJson()
    ->asJson()
    ->withToken($token)
    ->get('students');

Using Http is nice, but it seems like there's potentially a lot of duplicated code. How can one easily avoid the boilerplate configuration each/every time one wants to make a request?

Thanks...! :-)

Please sign in or create an account to participate in this conversation.