While working on a Laravel app, I ran into an annoying problem that I’m sure many of you have faced. I had created a few custom variables in my .env
file and was using them throughout my app with the env('VARIABLE_NAME')
function. It was working fine until I made some changes to the app. Suddenly, those variables stopped working, and I had to run a bunch of commands to clear the cache. It was a frustrating experience, especially since this wasn’t something I wanted to deal with in a production environment.
Here’s what I did, and how you can do the same to avoid these issues.
The Problem: Configuration Caching and env()
Variables
The issue is how Laravel handles environment variables. When you use env('VARIABLE_NAME')
directly in your code, it works great—until you change something in your app. Laravel caches the configuration to boost performance, but that cache doesn’t always pick up changes to the .env
file unless you manually clear it.
The Solution I Found
After some trial and error, I realized the key to avoiding these headaches is to use Laravel’s configuration files to manage env()
variables, rather than relying on env()
directly throughout the application.
1- Open your .env
file and define your custom variable like this:
GOOGLE_OAUTH_JSON_FILE_PATH=/var/www/oauth.json
...
2- Go to the config
folder, create a new file (e.g., google.php
) and add the following code:
<?php
return [
'gsc_json_file_path' => env('GOOGLE_OAUTH_JSON_FILE_PATH'),
...
];
3. Access the variable using config(FILE_NAME.NEW_VARIABLE)
$gsc_path = config('google.gsc_json_file_path');
That’s it. This change made my application more stable because it now relies on the cached configuration rather than directly querying the .env
file every time.
Why This Approach Worked Better?
Making this switch solved my problem in several ways:
- Improved Performance: Since Laravel caches the configuration, retrieving the variable using
config()
is faster and more efficient. - Enhanced Stability: The application became more reliable. I no longer had to worry about variables suddenly “disappearing” after making changes, and I didn’t need to constantly clear the cache.
- Following Best Practices: I learned that Laravel’s best practice is to use
env()
only within configuration files and rely onconfig()
elsewhere. This approach minimizes issues related to caching.
What to Do If You Need to Update Configuration?
Of course, there are times when you need to update the configuration in production. To ensure everything works smoothly, I used the following Artisan command to clear and re-cache the configuration:
php artisan config:cache
This command clears the existing configuration cache and re-caches everything, making sure my application is using the most up-to-date environment variables.