Clarifying the use of environment variables (.env) in a Laravel project
It is common to see the incorrect use of environment variables in some Laravel projects. Most projects correctly document the use of their Environment Variables, Laravel is not the exception.
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.
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.
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.
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
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
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.
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