wujt
wujt

Reputation: 1328

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.

Upvotes: 25

Views: 32064

Answers (5)

Ankush Sood
Ankush Sood

Reputation: 421

Just run

php artisan config:clear

It solved my issue.

Upvotes: 5

MOAZZAM RASOOL
MOAZZAM RASOOL

Reputation: 169

please use this its work for me use git bash or cmd and past this command

$ rm bootstrap/cache/config.php

this command clear cache folder

Upvotes: 6

MartiaHiblite
MartiaHiblite

Reputation: 80

In my case, it's just because I'm using php artisan serve, just restart it, the server command may read the env and keep at the startup time.

Upvotes: 1

wujt
wujt

Reputation: 1328

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.

Upvotes: 49

Majbah Habib
Majbah Habib

Reputation: 8558

Run those of command

composer dump-autoload
php artisan cache:clear
php artisan config:clear
php artisan view:clear

Now try to read

$value = env('VARIABLE_NAME');

if not working till now then,

Try another syntax to read env variable.

$value=getenv('VARIABLE_NAME');

Upvotes: 54

Related Questions