drewdan's avatar
Level 15

Http Client with Default Settings

Hey Guys,

Hoping you can help me. I am using the HTTP Client in L8, but I was wondering if there was a way I could set it so whenever I call the facade, there was always some default stuff passed with it I figured using a service provider might be the way to do it, but I get an error with some tests that the method fake() does not exist, so I guess, its returning an instance of pending request, rather than the factory, but I am not sure how to combat that when I take this approach, I tried to tap the factory, but this returns without the options.

public function register() {
		$this->app
			->bind(
				Factory::class,
				static fn ($app) => (new Factory)->withOptions(['proxy' => 'x.x.x.x']),
			);
	}

If anyone has some thoughts on how this might be achieved, I would be most greatful.

Ta, Andrew

0 likes
6 replies
bugsysha's avatar

I always create my own HttpClient which extends \Illuminate\Support\Facades\Http and I set everything in my class that I need.

2 likes
drewdan's avatar
Level 15

Thanks for the reply :) I figured that might be the approach to take. We already have the Http facade dotted throughout the application now, was hoping for a quick win without having to update all of the instances of it. Alas, this may be the only way!

bugsysha's avatar

It is not the only way, but it is the best way. If you do it through service container then if you add any custom methods to that class you will not have auto-completion.

xoctopus's avatar

@bugsysha Hi! Can u share ur solution? I'm having the same problem and I suppose creating a singleton would be ideal, but I can't find the most efficient way to do it. In my case, I have several client configurations and I suppose I would have to create a Singleton for each one. Please, if you have any solution, I would appreciate it if you shared it.

bugsysha's avatar

@xoctopus just rebind in the container.

1 Just create a class that extends Http client class that comes with Laravel:

class MyHttp extends \Illuminate\Support\Facades\Http
{
}

2 and then rebind it in the container:

$this->app->bind(\Illuminate\Support\Facades\Http::class, fn (): MyHttp => new MyHttp);

Please or to participate in this conversation.