Search code examples
laravelamazon-ec2

PHP's getenv not returning expected value in EC2 server


I'm trying to deploy to production my app that is working well in local.

The thing is, when try:

dd(getenv('APP_ENV'));

it returns "false"

but when I connect ssh and type:

php artisan env

I get

production

Any idea why it stopped working?

For the record, in production, my deploy script execute 3 commands:

composer dump-autoload -o
php artisan route:cache
php artisan config:cache

I mention it because it is possibly the only software config that is different.

EDIT: I identify that the problematic command is:

php artisan config:cache

If I do:

php artisan config:clear

problem is solved.


Solution

  • When using a cached config the .env file is not used anymore so getenv is useless, because the config is loaded from:

    bootstrap/cache/config.php
    

    Instead you can get the current environment from the loaded application configuration like so:

    config('app.env');
    

    Or directly using the app helper function:

    app('env');
    

    As a third option you can always use the environment method to get the current environment:

    app()->environment(); // or App::environment()
    

    Laravel uses the dotenv library internally to load the configuration keys from the .env file and add them to the environment variables using putenv, but when you cache your configuration that loading part is not done anymore because Laravel detects that there is a cache file present and uses that instead, so those keys from .env are not loaded into the environment, this not accessible via getenv.

    And because configuration values from the .env file are only cached when they are used in an actual configuration file from the config directory, you need to create a configuration option for them to be cached and accessible when you're using the cache.

    So if you want to have a BASE_URL key in your .env file with this value:

    BASE_URL=http://domain.com/
    

    If you want to be able to access its value when the configuration is cached, you need to use it in a configuration file. For example, you can add it to your config/app.php file like so:

    'base_url' => env('BASE_URL')
    

    Then you can access even when the configuration iit using:

    config('app.base_url')
    

    You can read more about accessing configuration values in the Laravel Documentation.