DEV Community

Antonios Thanasis
Antonios Thanasis

Posted on

🐱 Stop Using `env()` in Runtime Code

The Symptoms 😿

  • Jobs fail randomly
  • API calls return 401 Unauthorized

The "Solution" 🔄

php artisan config:clear

Then restart workers to pick up fresh environment values.

It works temporarily. Then fails again.


The Real Problem 🐛

The app was configured correctly. All env() calls lived inside config files. Config caching worked perfectly.

Then a developer added this directly in runtime code:

$newApiKey = env('NEW_API_KEY');

No config file entry. No config('services.new_api_key'). Just env() in the middle of a controller.

It worked fine in development because .env was being loaded on every request.

But in production, config:cache was running on every container restart. Laravel stops loading .env files when config is cached.

The config cache didn't have NEW_API_KEY because there was no config file for it. So env('NEW_API_KEY') returned null.

Boom. null → Unauthorized → crash.


Why config:clear "Fixes" It 🔁

config:clear removes the cached config file. Laravel starts loading .env fresh again.

env('NEW_API_KEY') works again → everything runs fine.

Until the next container restart runs config:cache and breaks it again.

It's a temporary bandage. Not a fix.


The Actual Fix ✅

  1. Add the new env variable to the proper config file

// config/services.php
return [
'api' => [
'key' => env('API_KEY', ''),
'new_key' => env('NEW_API_KEY', ''), // Add this line
],
];

  1. Use config() in runtime code

// ❌ Don't do this
$newApiKey = env('NEW_API_KEY');

// ✅ Do this instead
$newApiKey = config('services.api.new_key');

  1. Redeploy and cache

php artisan config:cache


The Results 🎉

  • ✅ No more random Unauthorized errors
  • ✅ No more config:clear bandages
  • ✅ New env variables work with config cache

The Lesson 🐾

If your fix is config:clear + restart, that's not a fix — it's a symptom.

One hard rule:

Every new env() call must first go through a config file.

  • config file ← env()
  • runtime code ← config()

No exceptions.


🐱 Remember

Config files are the bridge between .env and your code.

Break the bridge, break the app.

Now go fix your config.

Stop clearing. Start fixing.

Top comments (0)