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

angelorigo's avatar

PHP native env not reading .env variables

Hi,

I have started to maintain a legacy Laravel application wich runs on PHP 7.3. The database conection is not working. The env function at config/database.php is not reading the .env file at the root of the apllication. I use die(); at PDOConnection.php and the values i see are the values from the second parameter of the env function, not the values from the .env file. How can i get the values from the .env file?

0 likes
2 replies
LaryAI's avatar
Level 58

In a Laravel application, if the .env file is not being read correctly, it could be due to several reasons. Here are some steps you can take to troubleshoot and resolve the issue:

  1. Check the .env File Location: Ensure that the .env file is located in the root directory of your Laravel application. It should be at the same level as the artisan file.

  2. Clear Configuration Cache: Laravel caches the configuration for performance. If the .env file has been updated, you need to clear the configuration cache to ensure the changes are picked up. Run the following command:

    php artisan config:clear
    
  3. Check for Cached Environment Variables: If you have previously run php artisan config:cache, the environment variables are cached. You should clear the cache using:

    php artisan config:clear
    
  4. Verify .env File Permissions: Ensure that the .env file has the correct permissions and is readable by the web server user.

  5. Check for Syntax Errors: Ensure there are no syntax errors in the .env file. Each line should follow the KEY=VALUE format without spaces around the = sign.

  6. Ensure APP_ENV is Set Correctly: Make sure the APP_ENV variable in your .env file is set correctly. Sometimes, Laravel might not load the .env file if the environment is not set properly.

  7. Verify config/database.php: Ensure that the config/database.php file is correctly using the env function. For example:

    'connections' => [
        'mysql' => [
            'driver' => 'mysql',
            'host' => env('DB_HOST', '127.0.0.1'),
            'port' => env('DB_PORT', '3306'),
            'database' => env('DB_DATABASE', 'forge'),
            'username' => env('DB_USERNAME', 'forge'),
            'password' => env('DB_PASSWORD', ''),
            // other configurations...
        ],
    ],
    
  8. Check for .env.example: Ensure that your .env file is not mistakenly named .env.example or any other name.

  9. Restart the Server: Sometimes, simply restarting your web server (e.g., Apache, Nginx) or PHP-FPM can resolve the issue.

By following these steps, you should be able to resolve the issue of the .env file not being read in your Laravel application. If the problem persists, consider checking the Laravel logs for any errors that might provide more insight.

1 like

Please or to participate in this conversation.