I am using Laravel for a Github API project.
I want to set up a generic Guzzle client instance that has been pre-configured. I need this because with about 90% of my Guzzle requests, the Guzzle client will need an access_token header and a base_uri.
// Return a new configured guzzle client.
return new Client([
'base_uri' => 'https://api.github.com',
'headers' => [
'Authorization' => "token {$access_token}"
]
]);
I know I can bind this in the container I am currently doing it like so inside a custom middleware:
if (Auth::check()) {
$this->app->singleton(Client::class, function() {
// Grab the current user.
$user = Auth::user();
$access_token = decrypt($user->access_token);
// Return a new configured Guzzle instance.
return new Client([
'base_uri' => 'https://api.github.com',
'headers' => [
'Authorization' => "token {$access_token}"
]
]);
});
}
I am simply overriding the default Guzzle client with my pre-configured concrete instance. This works fine but the problem I am running into is that I can not do the following in a controller:
public function __construct(Container $container)
{
$guzzle = $container->make(Client::class);
}
If I use the above I will simply get the default implementation of Guzzle and not my pre-configured instance. I am guessing this it because the controller's constructor runs before the middleware and is it simply not set yet.
I still want to share the property to other methods in the controller though. How could I fix this?