log in
consulting hosting industries the daily tools about contact

config:cache will silently poison your env() calls

Running php artisan config:cache in production is correct. Calling env() directly in your code after that is a silent bug waiting to embarrass you.

If you call env() directly in your application code and you're also running php artisan config:cache in your deployment pipeline, you have a bug in production right now. It's not throwing errors. It's returning null and you probably have no idea.

What config:cache Actually Does

Laravel's config:cache command serializes every file in config/ into a single cached bootstrap file. After that runs, Laravel no longer reads your .env file at runtime. The values were baked into the cache at deploy time.

That's the intended behavior and it's good - it speeds up your app. The problem is that env() is a PHP helper that reads directly from $_ENV and getenv(). Once the config cache is active, those environment variables are no longer loaded by Laravel on each request. So env('SOME_KEY') returns null.

The official Laravel docs mention this. It's one of those things that's documented and still bites everyone eventually.

How the Bug Hides From You

Locally you're not running config:cache. You're using php artisan serve or Valet or Herd, your .env is loaded fresh on every request, and env() works fine. Everything looks good.

On staging you might not be running config:cache either, especially if staging is a quick-and-dirty setup. So it still looks fine.

Then production runs config:cache as part of a proper deployment pipeline, and suddenly a value that worked everywhere else is null. Depending on what that value controls - a payment gateway key, an API endpoint, a feature flag - this ranges from annoying to genuinely bad.

I ran into this on a healthcare client's project a couple years ago. We had a third-party lab results API endpoint stored in .env as LAB_API_URL. A developer had called env('LAB_API_URL') directly inside a service class rather than wiring it through config/services.php. Worked perfectly in every environment we tested. Hit production after a deploy and that service started returning empty responses. No exception, no log entry that made it obvious - just a null base URL being passed to an HTTP client that silently short-circuited. Took longer to find than I'd like to admit.

The Wrong Way

<?php

namespace App\Services;

use Illuminate\Support\Facades\Http;

class LabResultsService
{
    public function fetchResults(string $accessionId): array
    {
        // This works locally. Breaks silently after config:cache runs.
        $baseUrl = env('LAB_API_URL');
        $apiKey = env('LAB_API_KEY');

        $response = Http::withToken($apiKey)
            ->get("{$baseUrl}/results/{$accessionId}");

        return $response->json();
    }
}

Nothing in this code will throw. If $baseUrl is null, Guzzle will make a request to /results/abc123 against whatever base URL it defaults to, or fail silently depending on configuration. You won't get a helpful error.

The Right Way

All env() calls belong in config/ files. That's it. That's the rule. Your application code reads from config(). The config files read from env(). That separation is exactly why config caching works.

First, add your values to a config file:

<?php

// config/services.php
return [
    // ... existing entries ...

    'lab_api' => [
        'url' => env('LAB_API_URL', 'https://fallback.example.com'),
        'key' => env('LAB_API_KEY'),
    ],
];

Then in your service class:

<?php

namespace App\Services;

use Illuminate\Support\Facades\Http;

class LabResultsService
{
    private string $baseUrl;
    private string $apiKey;

    public function __construct()
    {
        // config() reads from the cache. This works correctly everywhere.
        $this->baseUrl = config('services.lab_api.url');
        $this->apiKey = config('services.lab_api.key');
    }

    public function fetchResults(string $accessionId): array
    {
        $response = Http::withToken($this->apiKey)
            ->get("{$this->baseUrl}/results/{$accessionId}");

        return $response->json();
    }
}

You can also inject config values through the service container if you want to be more explicit about dependencies, but even this simple change is enough to fix the problem.

Finding the Problem in an Existing Codebase

If you've inherited a Laravel project or you want to audit your own, grep is your friend:

grep -rn "env(" app/ --include="*.php"

Every result that isn't inside a constructor where you're explicitly not using config caching is a candidate for review. In my experience a codebase that's had multiple developers over a few years will have a dozen or more of these scattered through service classes, middleware, and event listeners.

PhpStan and Larastan can catch this too. If you're not running static analysis on your Laravel projects, start. It finds this class of bug at the same time it finds a lot of other things.

A Note on ServiceProviders

One place where calling env() is fine is inside a ServiceProvider::register() or boot() method, but only if you're doing something before config is loaded. In practice, almost nothing you write falls into that category. If you're in a service provider and you need a config value, still use config(). Don't make an exception "just this once" because it looks harmless.

The Detection Gap

What makes this particularly rough is the detection gap between environments. The standard progression is local works, staging works, production breaks. By the time you figure it out you've already shipped it.

The fix for the detection gap is to run php artisan config:cache in your staging environment too, and in your CI pipeline if you have one. If staging mirrors production's deployment process, you catch this class of bug on staging instead of production. This sounds obvious but a lot of small shops skip this because staging is under-resourced and manually deployed.

In our deployment scripts for NWOS-managed projects, config:cache runs in every non-local environment. No exceptions. That alone has caught this issue on staging several times before it reached production.

When This Matters Most

This bites hardest when the broken value controls something with a soft failure mode - an API endpoint that returns nothing, a feature flag that defaults to off, a logging destination that just drops writes. If your app throws an exception when the value is missing you'll find out fast. If it silently degrades, you might not find out until a client asks why a feature stopped working two weeks ago.

For anything that should be required at boot time, consider adding a check in a service provider:

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use RuntimeException;

class LabApiServiceProvider extends ServiceProvider
{
    public function register(): void
    {
        if (empty(config('services.lab_api.url'))) {
            throw new RuntimeException(
                 'services.lab_api.url is not configured. Check LAB_API_URL in your environment.'
            );
        }
    }
}

Loud failures beat silent ones every time.

When I'd Skip config:cache

Only on local development, and only because it's inconvenient to clear and rebuild the cache every time you tweak a .env value. Anywhere code is running that resembles production, the cache should be running too.

Some people skip config:cache entirely to avoid the problem. That's the wrong tradeoff. You're giving up a real performance improvement and working around a constraint that only exists because code is doing something it shouldn't.

Fix the code. Run the cache.


This is one of those issues where the framework did everything right - it's documented, the behavior is intentional and beneficial, and the fix is simple. It still catches experienced developers because the failure is silent and environment-specific. Grep your codebase for env( today, move those calls into config files, and add config:cache to every deployment that isn't your laptop. Twenty minutes of work, one less production incident.

Related

Need help shipping something like this? Get in touch.