DEV Community

Cover image for Fix Laravel app not reading values from .env file
Stephen Akugbe
Stephen Akugbe

Posted on

Fix Laravel app not reading values from .env file

I have been working on an application for a while now, and somehow one morning I noticed the application was no longer reading the Google recaptcha key from the .env file thus preventing me from gaining access to the system.
I thought I had tampered with my code somewhere, I looked back at the recent changes I made and none of them were related to the login aspect of the app.

Here is how I fixed it (I'm putting this out to help other developers as well as an easy access to my solution should I ever run into this kind of error again).

I initially ran the following commands but none of them fixed the issue.

php artisan optimize:clear
php artisan route:clear
Enter fullscreen mode Exit fullscreen mode

To fix the issue, I simply had to clear the configuration cache by running the following command:

php artisan config:clear
Enter fullscreen mode Exit fullscreen mode

and that was it, my application was reading the environment variables from the .env file.

If you found this article helpful, don't forget to leave a like.
Thanks for reading.

Top comments (4)

Collapse
 
tm69 profile image
tm69 • Edited

First you need to clear your cache with this command:

php artisan cache:clear
Enter fullscreen mode Exit fullscreen mode

Then you need to create a file in config directory called something like "google.php" and inside you need to return an array like this:

<?php

return [
     'recaptcha_key' => env('RECAPTCA_KEY', 'default_value'),
]
Enter fullscreen mode Exit fullscreen mode

and inside your .env file have declared:

RECAPTCA_KEY='value'
Enter fullscreen mode Exit fullscreen mode

With these definitions you can have cache values for your environment and in your code the right call for the values is this:

config('google.recaptcha_key')
Enter fullscreen mode Exit fullscreen mode

And then you can optimize your deployment.

Collapse
 
osalumense profile image
Stephen Akugbe

Thanks for this, I'll be sure to take note of this for subsequent projects

Collapse
 
codewithcaen profile image
CodeWithCaen

You should actually not call environment variables directly since Laravel will not read the .env file after caching. Clearing your cache does not solve the actual problem.

This is documented in the deployment documentation. laravel.com/docs/9.x/deployment#op...

Instead of calling your .env file directly, add a config key to your services.php file so you can benefit from caching.

Collapse
 
osalumense profile image
Stephen Akugbe

Thanks so much for this, I have actually implemented this in the application.