Different .env files for different environments in PHP


There exists great package for storing private and sensitive informations outside of your PHP code and it is called vlucas/phpdotenv. This package is also used by Laravel 5. Although I like the concept of storing delicate informations in separate file, I don’t like that Laravel 5 ditched Laravel 4 way of handling configuration for different environments where you created folder for each environment different than production and recreate configuration files and only the fields that needed to be changed (and also environment was detected based on machine name).

So the most obvious solution to this problem is creating two environment files (like .env and .env.prod) and every time you change environment you rename .env to .env.local and .env.prod to .env. But this isn’t quite elegant for me since changing filenames over and over again is not optimal.

Second solution I came across while searching the Internet is creating one global .env file and for each environment separate .env file (e.g. for local development it’s named .local.env). We put in global .env file only the keys that are independent from environment type (like APP_ENV, APP_KEY). And based on the APP_ENV value, we load additional environment file (if APP_ENV equals local, than beside loading .env file we also load .local.env file which has keys that will be used for local development). I think this approach is better because you only have to open .env file and rename APP_ENV to change environment (this is faster than renaming files as in first approach).

To take advantage of this second concept, just put the following code in bootstrap/app.php before returning statement:

Dotenv::load($app['path.base']);
$app->loadEnvironmentFrom(sprintf('.%s.env', env('APP_ENV')));

With second line we let Laravel do the work of loading additional .env file (and prevent it to reload global .env file which we do in first line).