A common problem while working in a team is some custom variables needed, when only one person on the team knows that they are needed, and then other people have errors because they don’t have that variable. Like API Tokens for 3rd party apps, default values for some function – basically, anything that should be in .env file. So here’s an instruction for you, how to put new environment variables correctly, without screwing up teammates work.
Let’s say we need to add a DEFAULT_CURRENCY variable and set that to USD. So here are the steps:
Step 1. Put it in .env.example
There is a file .env.example that should be pushed to the repository, while your local .env should be “gitignored”.
So, in that .env.example file you just put the key with empty value, like this:
That’s it. It will show your teammates that they need that variable, and they would figure out their local values to put into .env.
You may actually put a default value here, too, if they may have no idea what values are possible there.
Step 2. Put in in your local .env
This step is simple, just put the same line in your .env file.
Step 3. Put the key in config file
Now, don’t rush to use this variable as env(‘DEFAULT_CURRENCY’). Cause if you do that, and some teammate didn’t have this set up in their .env, they will get errors.
To avoid that, a good practice is to put all configuration variables in config/ files.
You should decide which of the files is most suitable for your case – it may be a default config/app.php, third party services are usually put in config/services.php, or you may create your own custom config/money.php. For this example, let’s do exactly that – here’s our config/money.php file:
return [ 'default_currency' => env('DEFAULT_CURRENCY', 'USD') ];
As you can see, we specify a default value USD as a second parameter here. This way, even if there’s no value set in .env, or even if there’s no .env file at all, the app won’t break.
Step 4. Use the value
Finally, here’s the correct way to use all we’ve done here:
// Correct way $currency = config('money.default_currency'); // Less correct way $currency = env('DEFAULT_CURRENCY');
Maybe “less correct” is not the right word here, but the point is that you should reference config values with config() function, and with this structure .env file isn’t even needed anymore. This way, your teammates won’t have any errors with your variables.
Some more info in these articles: