Home >Backend Development >PHP Tutorial >Configuring Laravel With Additional Environment Files
Laravel allows you to specify alternative environment files, bypassing the standard .env
file. This is particularly useful for testing, where a dedicated .env.testing
file can isolate test configurations. While not always necessary, this feature provides flexibility by leveraging the APP_ENV
environment variable.
The simplest application is using different environment files with Artisan commands or PHPUnit. To use a .env.demo
file, for instance:
# Create .env.demo cp .env .env.demo echo "\nEXAMPLE_SETTING=demo" >> .env.demo # Use the `demo` env php artisan tinker --env=demo # Or set APP_ENV APP_ENV=demo php artisan tinker
Laravel will prioritize .env.demo
over .env
.
.env.demo
instead of .env
.env.testing
For PHPUnit tests, the default is to use .env
. However, this can lead to conflicts with local development settings, especially concerning databases. While phpunit.xml
offers database configuration, using .env.testing
provides a cleaner approach.
phpunit.xml
sets APP_ENV
to "testing", prompting Laravel to load .env.testing
during feature tests:
<env name="APP_ENV" value="testing"></env>
Create .env.testing
and add test-specific settings:
cp .env .env.testing echo "\nEXAMPLE_SETTING=testing" >> .env.testing
To verify .env.testing
is loaded, add this to a test in tests/Feature
:
/** * A basic test example. */ public function test_the_application_returns_a_successful_response(): void { logger('Which environment file is Laravel using?', [ 'file' => $this->app->environmentFile() ]); $response = $this->get('/'); $response->assertStatus(200); }
Running phpunit
should log:
<code>[2024-05-24 00:22:42] testing.DEBUG: Which environment file is Laravel using? {"file":".env.testing"}</code>
Whether to version control .env.testing
(or use a sample .env.testing.example
) is a team decision. For CI, system-level environment variables are recommended for settings like test databases. Refer to the official Laravel documentation for more detailed environment configuration. For a deeper dive into the framework's implementation, examine the setEnvironmentFilePath
and checkForSpecificEnvironmentFile
methods in the Laravel source code.
The above is the detailed content of Configuring Laravel With Additional Environment Files. For more information, please follow other related articles on the PHP Chinese website!