Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

KSHIntern1's avatar

Laravel 5 loading wrong .env file

I use Laravel 5 and i have the following folders on my server:

/var/www/laravel_dev/
/var/www/laravel_stage/
/var/www/laravel_production/

They each have their own .env file and database, but for some reason each of them sometimes loads the wrong .env file (like once every 100th request).

I figured it loads the wrong .env file because when i dump the env database:
var_dump(env('DB_DATABSE'));
It some times return the name of the laravel_production database on the laravel_dev site.

I have made a grep search for the laravel_production database name, and it's not in the dev folder.

I have triede to dump the dir constant (__DIR__) various places, it's always correct, and my only solution is to set static values for the database connection.

Does anyone have an idea what could be wrong, or how i can dig further into what could be wrong?

0 likes
4 replies
alainbelez's avatar

i thought i am the only one having this problem. on my part sometimes, is it using the default database /user which is "forge"

seadev's avatar

I recently ran into this problem as well and wanted to share what I learned here since this is one of the top results in a Bing/Google search.

Chances are if you're running into this your running on a multi-threaded web server and it wasn't an issue until there where multiple people hitting the server.

Long story short, using the dotenv package that Laravel uses isn't thread safe. You can see a discussion about it here: https://github.com/vlucas/phpdotenv/issues/76

The quick fix is to run:

artisan config:cache

And I highly recommend adding a comment line to the top of your .env file:

# IMPORTANT! If you change ANYTHING in here make sure to run > artisan config:cache

I hope this helps.

4 likes
KSHIntern1's avatar

Sorry, i figured out an explanation for it on Stack Overflow in this discussion: http://stackoverflow.com/questions/32093709/laravel-5-0-33-loads-wrong-env-file/

It turns out that dotevn is only for development instances of the project. In production the config files have to be hardcoded.

https://github.com/vlucas/phpdotenv

"phpdotenv is made for development environments, and generally should not be used in production. In production, the actual environment variables should be set so that there is no overhead of loading the .env file on each request."

I use git on the production instance, so my solution for the problem is to set the environment variables in each vhost file for each instance i need on the server:

SetEnv DB_DATABASE laravel_stage SetEnv CACHE_PREFIX stage

I see you already commented on it :)

wyatt44's avatar

@SEADEV - Just spent two days attempting to debug this issue, caching it fixed everything! Thanks a million!

Please or to participate in this conversation.