laravelenvironment-variableslaravel-artisan

Laravel does not read env variables


I am having issues with env variables. For some reason, the helper env('VARIABLE') returns null every time I use it. It happened very unexpectedly and I don't know the reason. Restarting the Apache/IDE/computer does not work.


Solution

  • The solution is simple, but neither the IDE nor the debugger says anything about it. It just returns null. When you use php artisan config:cache, according to the documentation:

    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.

    Obviously I have env variables outside the config files, so after caching I was not able to use it outside anymore. The php artisan config:clear puts it back to work.

    What I've found more about the usage of env, that it should be used only within config files. You can access env variables from the rest of the project using other helper method config(). Be sure to assign it to another key in config file, e.g. 'key' => env('CACHE_DRIVER')

    What is more, you have to remember to run php artisan config:cache each time you will change .env file. Laravel will not load the new values, until it's cached. If it's not cached, no need to do it.