Use multiple .env files in Laravel

Load specific variables depending on the environment

In Laravel and other modern frameworks, you put your environment variables in a .env file at the root of your project. Most of the time, APP_ENV will be set to 'local'. Nothing new so far

PHPUnit, in phpunit.xml set this APP_ENV variable to 'testing'

If you run database test in phpunit, you can still use the phpunit.xml file to add more variables (specific database name, host, user, ...)

The problem is when you want to run full frontend test in the browser (with selenium for example), the setup become less clear. Do you create entities in the test? But then if you don't want it on your local database, you use the test database, but the automated test in the browser does not know that, and uses the other database

If you set up the environment to acceptance for example in the process (web server, built in php server, ...) that serves the acceptance environment, then Laravel will use a .env.acceptance if it exists. If it does not, it will fallback to the .env file

Can be handy if you don't use the same credentials in your team for your testing databases. Instead of having them in phpunit.xml, each team member can have them in their own .env.testing file

One thing though, if a key is already defined in phpunit.xml, any value with the same key in the env files will be ignored

Published over 2 years ago