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

JoaoHamerski's avatar

Laravel singleton doesn't work

So i put this code on the method register() inside the AppServiceProvider:

public function register()
{
    $this->app->singleton(GuzzleHttp\Client::class, function($app) {
        return new Client([
            'base_uri' => env('API_BASE_URI'),
            'headers' => ['X-API-Key' => env('API_KEY')],
            'curl' => [
                CURLOPT_SSL_VERIFYPEER => false
            ]
        ]);
    });
}

but when i do a new instance it simply doesn't work, i know that it doesn't work because on my controller i did:

$client = new GuzzleHttp\Client();

dd($client);

and the debugger page doesnt show the X-API-Key on the headers key that i put on the singleton closure, so, what am i doing wrong?

This is what it shows:

"headers" => array:1 [▼
    "User-Agent" => "GuzzleHttp/6.5.3 curl/7.68.0 PHP/7.4.3"
]

This is what should show:

"headers" => array:1 [▼
    "User-Agent" => "GuzzleHttp/6.5.3 curl/7.68.0 PHP/7.4.3"
    "X-API-Key" => "My API Key Here"
]
0 likes
5 replies
JoaoHamerski's avatar

Thanks, it worked, i didn't read the entire page of the documentation, my bad, but why don't use env helper outside of config files?

MichalOravec's avatar

From docs what I mentioned before

If you execute the config:cache command during your deployment process, you should be sure that you are only calling the env function from within your configuration files. Once the configuration has been cached, the .env file will not be loaded and all calls to the env function will return null.

1 like

Please or to participate in this conversation.