It works on your laptop. You deploy. Now your API key is null, and nothing in the code changed.

Very often the reason is one function: env().

What config:cache does

In production most Laravel apps run this during deploy:

php artisan config:cache 

It takes every file in config/ and writes them into one cached PHP file. Laravel loads that one file instead of many, so every request starts a bit faster.

There is one side effect. Once the config is cached, Laravel does not load your .env file anymore. The Laravel docs say it directly: after caching, env() only returns real system level environment variables.

So any env() call outside config/ now reads from nothing.

How the bug looks

Say a service calls a payment API:

// app/Services/PaymentClient.php class PaymentClient { public function charge(int $amount): void { $key = env('PAYMENT_API_KEY'); // fine locally, null after config:cache Http::withToken($key)->post('https://api.example.com/charges', [ 'amount' => $amount, ]); } } 

On your machine there is no cached config, so Laravel reads .env and $key has a value. In production the config is cached, .env is skipped, and $key is null. The request goes out with no token and the API answers 401.

The code did not change. Only the way Laravel boots changed.

The fix

Two rules.

1. Call env() only inside config files.

// config/services.php return [ 'payment' => [ 'key' => env('PAYMENT_API_KEY'), ], ]; 

When config:cache runs, this line runs once, reads the value, and the value is saved inside the cache.

2. Everywhere else, read it with config().

// app/Services/PaymentClient.php $key = config('services.payment.key'); 

config() reads from the cache in production and from the config files locally, so it gives the same answer in both places.

A check before every deploy

Search for env( outside config/:

grep -rn "env(" app routes resources database 

Anything it finds should move into a config file and be read with config().

You can also make your laptop behave like production for a minute:

php artisan config:cache php artisan serve 

If something breaks now, it would have broken after deploy. Clear it again when you are done:

php artisan config:clear 

One more thing to remember

After you change .env on the server, the app still uses the old cached values. Run php artisan config:cache again as part of the deploy, every time.

I build web apps in Laravel and MERN and design the system before the code. More of my work: https://github.com/Md-Foisal