Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getenv not working in EC2 Server

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

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 if do:

php artisan config:clear

problem is solved.

Tx!

like image 550
Juliatzin Avatar asked Mar 31 '16 22:03

Juliatzin


People also ask

What is the use of .ENV file?

env. example file documents the application's necessary variables and can be committed to version control. This serves as a helpful reference and speeds up the onboarding process for new team members by reducing the amount of time spent digging through the coding to figure out what needs to be set up.


1 Answers

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.

like image 132
Bogdan Avatar answered Sep 30 '22 04:09

Bogdan