[php] Laravel 5.2 not reading env file

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 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)

Clearly not pulling in my env config. This is affecting every single one of my config files, including third party 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 basically only copied in my app folder; no additional composer packages are included. Still having the same issue. I have other Laravel 5.2 projects on the same server that are working fine.

This question is related to php laravel environment-variables laravel-5.2

The answer is


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");

delete cache using:

    php artisan config:clear
    php artisan config:cache

I face the same problem much time during larval development. some times env stop working and not return any value. that reason may be different that depends on your situation. but in my case a few days ago I just run

 PHP artisan::config:clear

so be careful use of this command. because it will wipe all config data form its cache. so after that, it will not return any value. So in this situation, you need to use this first if you have run PHP artisan config:: clear command.

php artisan config:cache  // it will cache all data 
php artisan config:clear
Configuration cache cleared!

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

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.

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.


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
...

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.


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


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


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.


I ran into this same problem on my local, and I have tried all the answers here but to no avail. Only this worked for me, php artisan config:clear and restart server. Works like a charm!


When you fired command php artisan config:cache then it will wipe out all the env variables and env() will give null values, try running following command and boom there your env() again begin to catch all env variable

php artisan config:clear

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.


If you run this php artisan config:cache command on console then it will store all the .env file contents in cache, after this command if you append any contents into .env file the it will not be not be available until you run php artisan config:clear command


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


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

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.


Not sure whether is it already posted, but this combo worked for me:

php artisan clear-compiled 
composer dump-autoload
php artisan optimize

The simplicity is the power:

php artisan config:cache

You will receive:

Configuration cache cleared!

Configuration cached successfully!


run this:

php artisan config:clear
php artisan cache:clear

then
php artisan config:cache


For me the following worked

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

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.


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


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.


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.


Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to laravel

Parameter binding on left joins with array in Laravel Query Builder Laravel 4 with Sentry 2 add user to a group on Registration Target class controller does not exist - Laravel 8 Visual Studio Code PHP Intelephense Keep Showing Not Necessary Error The POST method is not supported for this route. Supported methods: GET, HEAD. Laravel How to fix 'Unchecked runtime.lastError: The message port closed before a response was received' chrome issue? Post request in Laravel - Error - 419 Sorry, your session/ 419 your page has expired Expected response code 250 but got code "530", with message "530 5.7.1 Authentication required How can I run specific migration in laravel Laravel 5 show ErrorException file_put_contents failed to open stream: No such file or directory

Examples related to environment-variables

Using Environment Variables with Vue.js Adding an .env file to React Project Is there any way to set environment variables in Visual Studio Code? Test process.env with Jest How to set environment variables in PyCharm? ARG or ENV, which one to use in this case? how to set ASPNETCORE_ENVIRONMENT to be considered for publishing an asp.net core application? What is a good practice to check if an environmental variable exists or not? Passing bash variable to jq Tensorflow set CUDA_VISIBLE_DEVICES within jupyter

Examples related to laravel-5.2

How to uninstall an older PHP version from centOS7 Extension gd is missing from your system - laravel composer Update How to fix error Base table or view not found: 1146 Table laravel relationship table? Setting selected option in laravel form How to clear Route Caching on server: Laravel 5.2.37 Where are logs located? Laravel 5.2 redirect back with success message getting error while updating Composer How to validate phone number in laravel 5.2? Laravel check if collection is empty