Laravel not reading changes to .env file
Asked Answered
H

27

180

After upgrading to Laravel 5.2, none of my .env file values are being read. I followed the upgrade instructions; none of my config files were changed except auth.php. They were all working fine in the previous version, 5.1.19

.env contains values such as

DB_DATABASE=mydb
DB_USERNAME=myuser

config/database.php contains

'mysql' => [
    'database' => env('DB_DATABASE', 'forge'),
    'username' => env('DB_USERNAME', 'forge'),
]

I get this error:

PDOException: SQLSTATE[HY000] [1045] Access denied for user 'forge'@'localhost' (using password: NO)

Not pulling in my env config. This is affecting every single one of my config files, including third parties such as Bugsnag.

I also tried

php artisan config:clear
php artisan cache:clear

Update

Trying php artisan tinker

>>> env('DB_DATABASE')
=> null
>>> getenv('DB_DATABASE')
=> false
>>> config('database.connections.mysql.database')
=> "forge"
>>> dd($_ENV)
[]

I have tried installing a fresh copy of Laravel 5.2. I only copied it into my app folder; no additional composer packages are included. I still have the same issue. Other Laravel 5.2 projects on the same server are working fine.

Hoyt answered 22/12, 2015 at 16:51 Comment(12)
Are you sure the .env file is named only .env? Not .env.example?Shool
Andrew are you editing the .env file by the forge interface or uploading it?Whity
@JamesElliott yes it is .envHoyt
Or are you running this locally? If your running under artisan serve you need to restart it just in case that might be the case.Whity
@MarkDavidson editing it through vi in the command line, and no it's on a full serverHoyt
Are the permissions correct on the file and readable by the web server user?Rechaba
@Rechaba yes, global read. I just tested changing owner to Apache just in case and that didn't help eitherHoyt
My .env file created by forge is 0664/-rw-rw-r-- and owned forge:forgeWhity
Do you use any custom functionality for env or config? For example custom environment detection, custom config merging etc?Karlotta
@MarcinNabiałek not that I can think ofHoyt
Please try dd(App::environment()); and tell us what is the output.Karlenekarlens
@ZakariaAcharki That outputs "production", regardless of what I set it to in .envHoyt
A
237

If any of your .env variables contains white space, make sure you wrap them in double-quotes. For example:

SITE_NAME="My website"

Don't forget to clear your cache before testing:

php artisan config:cache
php artisan config:clear
Affectional answered 13/3, 2016 at 5:42 Comment(3)
Yes It's working. After Changing any value in .env file run the php artisan config:cache & php artisan config:clear command. It will work.Lincoln
For Laravel8 use the same. In my special case only the "php artisan config:clear" was enough.Baccate
this helped me a lot.. I didnt know I should be running those config clears..Orbadiah
H
109

From the official Laravel 5.2 Upgrade Notes:

If you are using the config:cache command during deployment, you must make sure that you are only calling the env function from within your configuration files, and not from anywhere else in your application.

If you are calling env from within your application, it is strongly recommended you add proper configuration values to your configuration files and call env from that location instead, allowing you to convert your env calls to config calls.

Reference: https://laravel.com/docs/5.2/upgrade#upgrade-5.2.0

Humism answered 22/4, 2016 at 8:46 Comment(6)
php artisan config:cache solved it for me - nothing else had helped. Not even php artisan config:clear - thanks!Aluminium
Laravel 5.3 php artisan config:clear is the only thing that worked for meAntagonism
Laravel 5.4 - deployed on a VPS: php artisan config:clear worked for me. I didn't do config:cache before so it seemed a bit weird that I had to clear the cache.Linkage
github.com/laravel/framework/issues/…Castellan
make sure you're editing .env instead of .env.example fileHeldentenor
make sure you don't call config:cache before creating .env file :)Prue
P
68

For me it has worked this in this order:

php artisan config:cache
php artisan config:clear
php artisan cache:clear

And I've tried all the rests without luck.

Pentangular answered 5/3, 2019 at 7:41 Comment(1)
I think this removes the bootstrap/cache/config.php then you are not caching the configuration, that fix the issue at least for me, but I do not think it will be the best.Pinfish
H
47

Wow. Good grief. It's because I had an env value with a space in it, not surrounded by quotes

This

SITE_NAME=My website

Changed to this

SITE_NAME="My website"

Fixed it. I think this had to do with Laravel 5.2 now upgrading vlucas/phpdotenv from 1.1.1 to 2.1.0

Hoyt answered 22/12, 2015 at 19:38 Comment(3)
Same think - seems like spaces causes issues in .env under 5.2 where as in 5.1 it didn't.Underthecounter
And this is one of my (many) bugbears with Laravel: it has a habit of sometimes silently ignoring and accepting a variety of configuration and/or other types of errors, with no indication anything has gone wrong. Given, this may be a "feature" of phpdotenv, but Laravel still knows there's a .env file that needs to be included, and that it wasn't successful, but doesn't bother to tell anyone.Rotow
I've already wasted hours on something so silly. Thank you for stopping me waste more!Perrotta
T
28

I had a similar issue in my config/services.php and I solved using config clear and optimize commands:

php artisan config:clear
php artisan optimize
Teratogenic answered 1/9, 2016 at 14:2 Comment(1)
Note that artisan optimize builds a number of caches, including the config cache, as in the accepted answer.Robot
G
26

You can solve the problem by the following recommendation

Recommendation 1:

You have to use the .env file through configuration files, that means you are requrested to read the .env file from configuration files (such as /config/app.php or /config/database.php), then you can use the configuration files from any location of your project.

Recommendation 2: Set your env value within double quotation

 GOOGLE_CLIENT_ID="887557629-9h6n4ne.apps.googleusercontent.com"
 GOOGLE_CLIENT_SECRET="YT2ev2SpJt_Pa3dit60iFJ"
 GOOGLE_MAP="AIzaSyCK6RWwql0DucT7Sl43w9ma-k8qU"

Recommendation 3: Maintain the following command sequence after changing any configuration or env value.

 composer dump-autoload
 composer dump-autoload -o

 php artisan clear-compiled
 php artisan optimize

 php artisan route:clear
 php artisan view:clear

 php artisan cache:clear
 php artisan config:cache
 php artisan config:clear

Recommendation 4: When the syntax1 is not working then you can try another syntax2

   $val1 = env('VARIABLE_NAME');     // syntax1
   $val2 = getenv('VARIABLE_NAME');  // syntax2
   echo 'systax1 value is:'.$val1.' & systax2 value is:'.$val2;

Recommendation 5: When your number of users is high/more then you have to increase the related memory size in the server configuration.

Recommendation 6: Set a default probable value when you are reading .env variable.

 $googleClinetId=env("GOOGLE_CLIENT_ID","889159-9h6n95f1e.apps.googleusercontent.com");
 $googleSecretId=env("GOOGLE_CLIENT_ID","YT2evBCt_Pa3dit60iFJ");
 $googleMap=env("GOOGLE_MAP","AIzaSyCK6RUl0T7Sl43w9ma-k8qU");
Grilse answered 4/3, 2020 at 7:40 Comment(4)
Just wanted to add that it's a bad idea to add secrets to the code base (see recommendation 6).Carilla
This is not real client & secret id, I have given a draft information to make understand the solution finder. Thanks @CarillaGrilse
That's not what I meant. If you're passing secrets as a second parameter to the env() method, that means you're adding these secrets to your repository, thus breaking the best practice not to include .env values in the repository.Carilla
please be careful: recommendation 6 is not a good practiceAmericaamerican
R
12

I missed this in the upgrade instructions:

Add an env configuration option to your app.php configuration file that looks like the following: 'env' => env('APP_ENV', 'production')

Adding this line got the local .env file to be read in correctly.

Rotow answered 22/4, 2016 at 14:32 Comment(1)
I guess I got the same error, since my app was Laravel 4, then upgraded to 5.0, then to 5.1, etc. Probably missed adding this value in my app.php. Thanks for saving me a lot of time. Here's an upvote!Antonantone
V
12

I had the same issue on local environment, I resolved by

  1. php artisan config:clear
  2. php artisan config:cache
  3. and then cancelling php artisan serve command, and restart again.
Victualage answered 22/6, 2018 at 7:47 Comment(0)
L
7

Same thing happens when :port is in your local .env

again the double quotes does the trick

APP_URL="http://localhost:8000"

and then

php artisan config:clear
Lamonica answered 28/2, 2019 at 16:31 Comment(0)
M
4

In my case laravel 5.7 env('APP_URL') not work but config('app.url') works. If I add new variable to env and to config - it not works - but after php artisan config:cache it start works.

Muttra answered 30/4, 2019 at 21:14 Comment(4)
If you are on development enviroment you shouldn't cache your config and routes. To remove all cache you can use: php artisan optimize:clearScraggly
@ZohaibHassan How to turn off cache for config and routes on dev environment?Leeannaleeanne
Above command will turn off 1. routes cache, 2 config cache, 3. clear views 4. clear optimized files 5. clear cache if anyScraggly
For config only you can use php artisan config:clear it will clear your config cache and will not generate again and when you go on production you can run php artisan config:cache to cache your configurationsScraggly
C
3

Also additional to what @andrewtweber suggested make sure that you don't have spaces between the KEY= and the value unless it is between quotes

.env file e.g.:

...
SITE_NAME= My website
MAIL_PORT= 587
MAIL_FROM_NAME= websitename
...

to:

...
SITE_NAME="My website"
MAIL_PORT=587
MAIL_FROM_NAME=websitename
...
Consort answered 16/6, 2017 at 10:58 Comment(0)
O
3

if you did call config:cache during local development, you can undo this by deleting the bootstrap/cache/config.php file. and this is work for me.

Officeholder answered 8/8, 2018 at 11:51 Comment(0)
W
3

I experienced this. Reason was that apache(user www-data) could not read .env due to file permissions. So i changed the file permissions to ensure that the server (apache) had read permissions to the file. Just that and boom, it was all working now!
Update:
How to do this varies, depending on who owns the .env file, but assuming it belongs to the Apache www-data group, you can do this:

sudo chmod g+r .env

Modify it depending on your permission structure.

Wallasey answered 27/10, 2018 at 8:26 Comment(1)
So i changed the file permissions to ensure that the server (apache) had read permissions to the file. this is actually wrong approach. You should have fixed apaxhe config so it serves this particular site as owner that owns these filesSeafowl
B
3

I know this is super old, but today I discovered another reason why my .env was not loaded:

  • I had a (commited) .env.local
  • I recently switched APP_ENV from dev to local

With L8 (and maybe before), what happens is that it tries to find .env.<APP_ENV> and if it finds it, uses it.

Fun fact: in my case, .env.local was a blue-print file with non-sensitive information and not meant to be directly used, but that's what happened.

Removing the .env.local led to Laravel looking for .env instead.

Bulb answered 22/2, 2023 at 9:8 Comment(0)
P
2

I solved this problem generating a new key using the command: php artisan key:generate

Proselyte answered 5/9, 2017 at 8:41 Comment(1)
Warning: DON'T do this in a already deployed site. Otherwise all the already encrypted data will not be accessible. Read first the Laravel documentation regarding data encryption before attempting this in production environments.Macaronic
N
1

if you did call config:cache during local development, you can undo this by deleting the bootstrap/cache/config.php file. and this is work for me.

@Payal Pandav has given the comment above.

I want to tell a simple workaround. Just edit the config.php file in the bootstrap/cache/ folder. And change the credentials. This worked for me. Please don't delete this file since this may contain other crucial data in the production environment.

Nagual answered 14/3, 2019 at 6:55 Comment(0)
Y
1

In my case, I needed to restart my Supervisord jobs (i.e. my queue workers). After doing so, a new environment variable I had added to my .env file was successfully pulled into my application.

Remember, queue workers, are long-lived processes and store the booted application state in memory. As a result, they will not notice changes in your code base after they have been started. So, during your deployment process, be sure to restart your queue workers. In addition, remember that any static state created or modified by your application will not be automatically reset between jobs.

Source: Official Laravel Docs - Queues

Yorgos answered 13/1, 2022 at 16:9 Comment(0)
S
1

If you've come here because you have multiple .env.* files and php artisan config:cache resulted in incorrect settings, it's because it (tried to) read the .env file and not the one specific to your environment. Try this instead (where CODE corresponds to .env.CODE):

APP_ENV=CODE php artisan config:cache
Still answered 10/1, 2023 at 4:8 Comment(0)
K
0

In my case I was using VSCODE and it turned out my .env file was auto-dectected by the IDE as a shell script file and not an Ini which was causing me the issue. It's a rare occurrence, but I hope it will save someone time.

Kuykendall answered 12/7, 2022 at 14:32 Comment(0)
A
0

For Laravel coder. We can use config() to solve this problem

in file "config/app.php":

'same_url' => env('SAME_URL', 'http://localhost'),

in your code base:

$sameURL = config('app.same_url').'/orders/';
Aun answered 12/9, 2022 at 3:6 Comment(0)
D
0

For those who run their php application in Docker it might help to run config:clear and then restart the container, so the worker processes restart as well (if they're configured to run inside the same container as the application)

Demijohn answered 24/10, 2023 at 13:51 Comment(0)
C
0

For anyone encountering issues with Laravel Valet where php artisan does not reflect updated .env variable values, consider using a unique naming convention for your environment variables as a workaround.

For instance, instead of using the default DB_USERNAME, rename it to DATABASE_USERNAME or another distinctive name. The root cause of the issue, where php artisan tinker still displays outdated values even after executing the commands:

php artisan cache:clear
php artisan config:clear
php artisan view:clear

is unclear. This workaround can help bypass the problem by ensuring your application references uniquely named environment variables, potentially avoiding conflicts or caching issues with commonly used names.

refer: https://laracasts.com/discuss/channels/general-discussion/env-not-reading-variables-sometimes

Cottontail answered 28/2 at 23:39 Comment(0)
A
-1

I made the mistake by doing dd/die/dump in the index.php file. This causes the system to not regenerate the configs.

Just do dump in view files will do. The changes to .env file update instantly.

Akerley answered 24/1, 2019 at 8:46 Comment(0)
S
-1

I had some problems with this. It seemed to be a file permission issue somewhere in the app - not the .env-file.

I had to - stop my docker - use chown to set owning-rights to my own user for the whole project - start docker again

This time it worked.

Salesroom answered 14/4, 2020 at 17:54 Comment(0)
T
-1

If you're using sail environment right after you change your environment variable just restart a server, otherwise it's going to show the old value.

Torras answered 16/8, 2021 at 12:7 Comment(0)
Q
-1

In my case (Laravel 7.x) it happen because I had set environmental variable on server. To be precise in Docker container. And because environments variables are higher priority than .env file, nothing changes during .env file edit.

Check if you set the env variable on the server:

echo $VAR_NAME
Querist answered 24/9, 2021 at 15:22 Comment(0)
G
-3

Tried almost all of the above. Ended up doing

chmod 666 .env

which worked. This problem seems to keep cropping up on the app I inherited however, this most recent time was after adding a .env.testing. Running Laravel 5.8

Gullah answered 29/10, 2019 at 16:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.