Michael Dyrynda
Home Blog Podcasts
Environment variables, config caching, and Laravel February 6th, 2017

You should typically run the php artisan config:cache command as part of your production deployment routine.


As part of the recommended production deploy process it is important to run the caching commands that Laravel affords us via Artisan. This means running config:cache and route:cache, which will compile the config and route files down into a single file each.

In doing so, Laravel aims to speed up parsing of these files by only needing to read a single, rather than multiple files.

Why caching helps

Think of it like this: each time a visitor makes a request to your site, Laravel boots your application up. As part of this process, Laravel spins through each of the files in your config directory - 11 files in a default 5.4 install - loads them into memory, resolves any computations, pulls variables from the environment, etc.

With your routes, Laravel must compile your routes file(s) down into a collection that the route matching component can work with. When caching your routes, Laravel will serialize the routes into a single file so that again, loading the routes from a single file is much more efficient. Laravel 5.4 has vastly improved route compilation as well, meaning that even with a large (1000+ routes) application, compiling and matching routes should be very fast.

What about environment variables?

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.

Environment variables that are loaded from the .env file - not those that are loaded from FPM or nginx - are read only when a cached configuration file does not exist; that is, once you run the config:cache Artisan command, Laravel will no longer load the .env file.

For your application, once the configuration is cached, if you happen to be referencing environment variables directly throughout your application using the env() helper, rather than values assigned to configurations files within the config/ directory and subsequently the config() helper, they'll simply return the default null value.


I'd suggest you assign all of your environment configuration to app configuration files as documented, either in config/app.php or more specific files as necessary in all instances, whether you are using the .env file or FPM/nginx-injected environment variables.

This gives you a consistent way of accessing all of your configuration. In this way, you needn't worry about accidentally referencing environment configuration that winds up being null.

I'm a real developer ™
Michael Dyrynda


I am a software developer specialising in PHP and the Laravel Framework, and a freelancer, blogger, and podcaster by night.

Proudly hosted with Vultr

Syntax highlighting by Torchlight