'How to load different .env file in laravel 8
I need to load a different .env file, named .env.staging under certain conditions.
In .env file
APP_NAME="Laravel"
APP_ENV=staging
APP_KEY=
APP_DEBUG=true
APP_URL=
But my .env.staging file is not loaded. How to load different .env
Solution 1:[1]
Test my way: Create env folder in root folder with 2 environement files.
Content of env\.env.staging:
APP_NAME="STAGING MODE"
APP_KEY=base64:AjYSIS9myYGnVkdfaXy2Oz6lY/ofyNhuqN9ZtkKaNm0=
APP_DEBUG=true
APP_URL=http://localhost
Content of env\.env.test
APP_NAME="TEST MODE"
APP_KEY=base64:AjYSIS9myYGnVkdfaXy2Oz6lY/ofyNhuqN9ZtkKaNm0=
APP_DEBUG=true
APP_URL=http://localhost
Then set this code to boot file bootstrap\app.php:
<?php
use Dotenv\Dotenv;
$app = new Illuminate\Foundation\Application(
$_ENV['APP_BASE_PATH'] ?? dirname(__DIR__)
);
// Load temporary environement variables
$dotenv = Dotenv::createImmutable(__DIR__, '../.env');
$dotenv->load();
// Get dynamic APP_ENV wrote in .env file
$env = $_ENV['APP_ENV'];
// You can debug by command var_dump to check
// var_dump($env);
switch ($env) {
case 'staging':
// Overwrite existing environement variables
$dotenv = Dotenv::createMutable(__DIR__ .'/../env', '.env.staging');
$dotenv->load();
break;
case 'test':
// Overwrite existing environement variables
$dotenv = Dotenv::createMutable(__DIR__ .'/../env', '.env.test');
$dotenv->load();
break;
default:
break;
}
Create a route with a view has this title:
<title>{{ env('APP_NAME') }}</title>
When you change variable APP_ENV in .env file:
APP_ENV=test
You will get the title “TEST MODE”
If you change to:
APP_ENV=staging
You will get the title “STAGING MODE”
The title changed, mean the environement variables are loaded!
Tested with "laravel/framework": "^8.75" version has built-in package "vlucas/phpdotenv": "^5.4.1".
Solution 2:[2]
To use the .env.test file try to restructure your initial bootstrap() method inside of the App/Http/Kernel.php file to look like this:
public function bootstrap()
{
app()->loadEnvironmentFrom('.env.staging');
parent::bootstrap();
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | protoproto |
| Solution 2 | Mansjoer |
