php - Laravel - Load different .env file
Solution:
I just figured it out: The default .env file is being loaded inside of the bootstrap()
method of LoadEnvironmentVariables.php.
To use the .env.test file I had to restructure my initial bootstrap()
method inside of the App/Http/Kernel.php file to look like this:
public function bootstrap()
{
app()->loadEnvironmentFrom('.env.test');
parent::bootstrap();
}
So the essential part was to move the parent::bootstrap()
call below the loadEnvironmentFrom()
call.
Answer
Solution:
Instead of doing any code change, you can use export command create a file called .env.test, you want to sue this as .env file use terminal
APP_ENV=local
php artisan config:cache
php artisan key:generate
This below edit is to explain how .env file is getting set
In Illuminate\Foundation\Application
class has method loadEnvironmentFrom
which is taking the file as parameter and setting it,
you can use bootstrap/app.php
after you are getting $app
$app = new Illuminate\Foundation\Application(
$_ENV['APP_BASE_PATH'] ?? dirname(__DIR__)
);
here you will be having instance of Illuminate\Foundation\Application
you can just call the loadEnvironmentFrom function like
$app->loadEnvironmentFrom('.env.local');
May be it is better to use Kernel.php instead of this, I do not think either of bootstrap/app.php or kernel.php will get overridden with composer update
, so make more calculation while using it. I have added this, so that it will help you understand the stuffs.
Answer
Solution:
You can load a different environment file using APP_ENV
For example if APP_ENV=test
then .env.test
can be loaded.