Hey, my book is finally available. Find it here.  Eloquent Beyond The Basics!

You should never use env() outside of your config files

Feb 2, 2022

I've seen a couple of questions on laravel forums that look something like this.

.env Not Reading Variables Sometimes

env() / getenv() Sometimes Not Initialized

.Env file I changed DB name but not reflected

Maybe this has happened to you.

By the end of this post hopefully, you will know why this is happening and how to avoid it.

Config cache

The laravel deployment documentation page mentions optimizing the configuration loading, if you follow the documentation you'll probably run the following command when deploying your website to production:

php artisan config:cache

You might be asking, what does this have to do with the env() function?

Well, when you cache the configuration laravel joins all your configurations into a single file for better performance, but another effect this command has is that laravel will stop reading your .env file. This means that the env() function will not return any value you have in your .env file.

Does that mean that you should stop using your .env file at all?

Well no, it only means that you should stop using the env() function in your code and instead only use it in your config files.

Instead of doing something like:

Stripe::setApiKey(env('STRIPE_API_KEY'));

You would do:

Stripe::setApiKey(config('services.stripe.api_key'));

And then add the env call to your config file:

// config/services.php
return [
...
    'stripe' => [
        'api_key' => env('STRIPE_API_KEY'),
    ]
];

Now everything should work as expected.

What if you want to change your .env file in production?

In that case, you can run the cache command again after you change the file:

php artisan config:cache

If for some reason you need to delete the cache you can do it with:

php artisan config:clear