DEV Community

StuartCreed
StuartCreed

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
// Production specific content...
@endproduction

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

@env('staging')
// The application is running in "staging"...
@endenv

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

Reasons:

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:

https://stackoverflow.com/questions/42935205/laravel-does-not-read-env-variables

“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:

https://laravel.com/docs/8.x/configuration#configuration-caching

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)

Collapse
 
abdoahmed111 profile image
ABDELRHAMAN AHMED ABBAS

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