AndrielAndy's avatar

Laravel - Load different .env file

I need to load a different .env file, named .env.test under certain conditions.

I attempted to do that through a middleware by adding

app()->loadEnvironmentFrom('.env.test');
Dotenv::create(base_path(), '.env.test')->overload();

to the bootstrap() method of Kernel.php. I also tried to create a dedicated middleware for this and load it as the first one in the web middleware group. But either way, it is loading the standard .env file.

It works if I do it in the /bootstrap/app.php file but I really don't want to put it there.

0 likes
5 replies
aurawindsurfing's avatar

I think it was depreciated in version 5. The way to do it is to use:

APP_ENV=local
APP_ENV=production

in your single .env file.

Can you not put the correct .env on the actual production server?

martinbean's avatar

@andrielandy The .env file just contains variables that should be interpreted as environment variables at runtime. Your application should not be swapping environment files because they replace actual environment variables in environments where it’s not possible or difficult to use them, such as on your computer or on shared hosting.

If you need to set different values for different environments then do so. If it’s for running tests, then you can add entries to your phpunit.xml file and those will be made available to your application when running tests.

thewebartisan7's avatar

There is some hacking solution that you can use, but as martin said is better not use in production.

I am using it only locally for test different database or other different settings.

There are several solutions that I found, the most easy is to edit bootstrap/app.php, adding:

// This code is already in app.php
$app = new Illuminate\Foundation\Application(
    $_ENV['APP_BASE_PATH'] ?? dirname(__DIR__)
);

// This is your custom
$yourCondition = 'local'
switch($yourCondition) {
    case 'local':
        $app->loadEnvironmentFrom('.local.env');
        break;
    default:
        $app->loadEnvironmentFrom('.env'); // Or just do nothing
        break;
};

Solution from https://github.com/laravel/framework/issues/23511#issuecomment-426676595

Then there is this gist: https://gist.github.com/msankhala/3c282abf546318a2662e

But it's a bit more complicated.

jamesmuldrow@gmail.com's avatar

7 months late to this party, but I did write a program to swap my environments in Laravel. I still use it every project, mainly because i run Laravel and Lumen in docker containers and sometimes I want to run commands outside of the container. So my dev box is normally set up with .env.local and my docker containers would use configs from .env.docker. Either way, if this tool is helpful to anyone feel free to use it.

https://github.com/jamesmuldrow/laravelEnvironmentSwapTool

Please or to participate in this conversation.