Laravel 5 doesn't read values from dot ENV fil

2019-03-05 21:13发布

问题:

I don't know if this question is relevant or not. LARAVEL 5 is still in developmental phase. I have pulled LARAVEL 5 after watching one of the Laracast video about new features in LARAVEL 5. I couldn't resist to wait for its formal release.

I named the local environment dot file as .env.local.php. But for some reason I am unable to get the the values from this dot file when using $_ENV['KEY'].

I am quite sure that I have configured the environment correctly. When doing $app->environment() shows the correct environment. Has it been changed in LARAVEL 5 the way we get the values from dot files or am I missing something ?

回答1:

By default in environment.php file you have something like that:

if (file_exists(__DIR__.'/../.env'))
{
    Dotenv::load(__DIR__.'/../');
}

so only .env file is being read (notice .env not .env.php - so you should rename your file - or you can add as 2nd parameter file name .env.php if you want). Any other environment files (.local.env) are not being read by default - you will need to load them manually.

If you don't have such code by default, you should probably update/install Laravel 5 again (changes appear very often)

Now, I don't know what method you use, but you can put in your .env file also your environment name in for example APP_ENV variable, create .local.env file with content you want and then you could use in environment.php file:

if (file_exists(__DIR__.'/../.env'))
{
    Dotenv::load(__DIR__.'/../');

    if (getenv('APP_ENV') && file_exists(__DIR__.'/../.' .getenv('APP_ENV') .'.env')) {
        echo "loading";
        Dotenv::load(__DIR__ . '/../', '.' . getenv('APP_ENV') . '.env');
    }

}

If you don't want to do it this way, you can probably change the other and load env file you want based on $env assuming you use PC based environment detection.

If it's unclear you can also look at What's the correct way to set ENV variables in Laravel 5?