3

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?

2
  • The controller shouldn't be running before the middleware unless the middleware is designed to run after the response has been created. In either case though, you should be putting it into a service provider. Commented Dec 30, 2016 at 19:50
  • @user3158900 I need to set it up with the access token of the user that is currently logged in though. How can I get the Auth::user() inside a service provider though? Commented Dec 30, 2016 at 20:16

1 Answer 1

1

I would create a new class for api interactions. In the constructor, initiate your guzzle object and then create methods for various api calls that use that guzzle object.

Sign up to request clarification or add additional context in comments.

2 Comments

Let's I do end up doing this, where would I bind the concrete implementation of my class in the container? Or would you just skip the container?
Sorry, I either don't fully understand what you mean or I'm just not familiar with containers.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.