Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

ahoi's avatar
Level 5

Elegant way to access API using OAUTH

Hello everybody,

at the moment I am connecting my Laravel application to a 3rd-party API using this in every controller method (this is an API-controller aswell):

public function view(Request $request, $id){

        try {
              $client      = new Client();
              $accessToken = $this->client->getAccessToken();
              $response    = $client->request('GET',
                  'https://'.config('api.server')
                  .'/api/category/index?length=-1', [
                      'headers' => [
                          'Accept'        => 'application/json',
                          'Authorization' => 'Bearer '.$accessToken,
                      ],
                  ]);
          } catch (BadResponseException $e) {
              return response()->json(['message' => $e->getMessage()], $e->getCode());
          }

          $response = $response->getBody();
}

This means that I create a new token every time I am triggering my Controller. Is there a "Laravel-like" way to create an access token and create a new instance of a client without adding it over and over again in each method of the controller? I thought about an middleware, but I'm not sure about this.

0 likes
1 reply
skauk's avatar
skauk
Best Answer
Level 8

@ahoi You could create a class where you instantiate the client and add a generic method that calls the API getting the access token automatically. You can then register this class with the service container and use it anywhere in your app. You can register it a singleton to avoid getting a fresh token every time, although the client usually takes care of this.

1 like

Please or to participate in this conversation.