DEV Community


Posted on

How to reference an .env variable correctly in laravel

Use env('something') in your config files, but no where else (it will return null). Use config() to reference a config file if you need to access a .env variable outside your config files.

If you need to get the environment directly, you can use app()->environment() or if in blade use the Environment Directives:

You may check if the application is running in the production environment using the @production directive:

// Production specific content...

Or, you may determine if the application is running in a specific environment using the @env directive:

// The application is running in "staging"...

@env(['staging', 'production'])
// The application is running in "staging" or "production"...


Unfortunately we can’t use env(‘something’) outside of a config file because when the cache is optimised etc it will not work, even though it does work on your local.

By cache optimisation I mean: php artisan optimize

See this thread for more information:

“If you execute php artisan config:cachecommand during your deployment process, you should be sure that you are only calling the env() function from within your configuration files.”

php artisan config:cache is done as part of php artisan optimize

This is warned of here:

You can access env variables from the rest of the project using other helper method config(). You can then assign the key in the config file to the env file, e.g. 'key' => env('CACHE_DRIVER')

Top comments (1)

abdoahmed111 profile image

I'm working on full stack app using laravel and react, and I want to use a variable in .env file in react application.
which it didn't work on production like you said.
any idea how to do this?
Thanks in advance