Clarifying the use of environment variables (.env) in a Laravel project
If you still don't know why your variables saved in your .env
file return as null
after executing php artisan config:cache
, don't worry, now I'll explain why.
The reason
Let's first define the concept 'Environment Variable'. We call environment variables those variables that are stored in the .env
file of your project. The central idea of this type of variable is to simplify the task of project configuration in various environments, where the environment is the server or service where the project is placed or hosted.
It is common to see the incorrect use of environment variables in some Laravel projects. My understanding about this is because, in other popular languages such as Node.js or Javascript, they use these files to host this information directly. The difference is that many times, projects and/or languages that have the use of these variables directly, usually compile the project before being put into production, which replaces these values in the source files before being public. The important thing about this is to understand what happens in each framework or language used. Most projects correctly document the use of their Environment Variables, Laravel is not the exception.
Given the convenience that exists in being able to write and access a variable of this type almost in a 'global' way, it is very common for programmers to use them to store sensitive data that needs to be used or updated quickly.
The problem is that this 'informal' use is not the 'correct' use. In Laravel, the use of environment variables is for the sole purpose of feeding configuration files. Although it is possible to use these variables in your code through the .env
function, it is important to understand that this is not the correct use of them and it is the reason why errors can be generated when placing our project in production.
Production
To understand the problem, it is important to understand what happens when a project is published in production. Laravel's good practices include creating a cache of frequently used settings and files on the system. This task is possible thanks to the artisan
: config:cache
and optimize
commands that have the purpose of preparing the system to be optimal in its service.
In Laravel, the main purpose of the config:cache
command is to move the Environment Variable values to their final variables in the configuration files and set the existing Environment Variables to null
.
For this reason, after executing this command, any document outside the config
folder that tries to access these variables through the .env
function will receive null
as a response.
Recommended Solution
If you require or want to configure protected variables to be used within your application, it is recommended to create a configuration file that accesses the environment value(s) required in your application and access these values through the config()
function.