The SAFE Way to Use .env Variables in Laravel

When developing with Laravel, accessing configuration values and sensitive information from the .env file in your code is common. In this article, we will explore the importance of using the config() helper function and why you should avoid using the env() helper when reading the values. Additionally, we’ll cover how to add your own env variables to configuration files and integrate them seamlessly using the config() helper.

To read a variable from the .env file you should use the config() helper function. An example of this is: config('app.name'). The values which are available to config() are set in configuration files in the /config folder. Inside such a configuration file it is typically set using the env() helper.

The reason we can’t use env() directly throughout the application is that it will return empty values whenever your configuration is cached. Note that caching your config is recommended in a production environment as stated in the Laravel docs. The command to properly cache your config is:

php artisan config:cache
The Output of Running php artisan config:cache

The command above instructs artisan to generate a file in /bootstrap/cache/config.php which contains all values in a format that is optimized for speed.

The following command will clear the cache again by deleting the /bootstrap/cache/config.php file:

php artisan config:clear
The Output of Running php artisan config:clear

In addition to the config() helper function you can use the Config facade which Laravel also provides. This would look like

// This is the most common and recommended way:
$appName = config('app.name');

// This is an equivalent:
use Illuminate\Support\Facades\Config;
$appName = Config::get('app.name');

// But avoid this:
$appName = env('APP_NAME');

How to Add Your Own Env Variable to the Laravel Configuration

To add your custom environment variable and make it accessible throughout your application, follow these steps:

  1. Open your .env file and define your custom variable like this:
.env
YOUR_VARIABLE=value
  1. Within the config folder, create a new file (e.g., custom.php).
  2. In the newly created file, define an array that returns the value of your environment variable:
config/custom.php
return [
    'your_variable' => env('your_variable'),
];
  1. You can now access the value by using the config() in your Controller code:
$value = config('custom.your_variable');
  1. You can also access the value in your Blade code by using the config():
<a href="{{ config('custom.your_variable') }}">Link</a>

Note that it is not always necessary to make a new configuration file. Often it makes sense to add your setting to one of the existing ones. For example, adding a second database could be added to database.php, and adding a REST API with URL and login credentials would best be added to services.php. See our next section for an exhaustive list of Laravels’ default config files.

Where are the Laravel default config files?

Laravel ships with a set of default config files. These provide values used for the framework’s operation and can be extended with your own custom configuration values.

A fresh Laravel installation provides the following config files:

Config FileLocationPurpose
app.php/config/app.phpApplication-level configuration settings
auth.php/config/auth.phpAuthentication configuration
broadcasting.php/config/broadcasting.phpBroadcasting configuration for real-time event broadcasting
cache.php/config/cache.phpCache configuration
cors.php/config/cors.phpCross-origin resource sharing (CORS) configuration
database.php/config/database.phpDatabase connection and configuration settings
filesystems.php/config/filesystems.phpFilesystem configuration
hashing.php/config/hashing.phpHashing configuration for password hashing
logging.php/config/logging.phpLogging configuration
mail.php/config/mail.phpEmail configuration
queue.php/config/queue.phpQueue configuration
sanctum.php/config/sanctum.phpConfiguration for Laravel Sanctum (Authentication API)
services.php/config/services.phpConfiguration for external services
session.php/config/session.phpSession configuration
view.php/config/view.phpView configuration

Why you should use Laravel config files

We have already discussed the limitations of using the env() helper with caching. However, there are several additional advantages to consider.

The reasons to use config files, instead of the .env file directly are:

  1. Organization: Config files provide a structured way to manage and organize configuration settings. They allow you to group related settings together, making it easier to locate and update them.
  2. Version Control: Config files can be easily tracked and managed with version control systems like Git. This ensures that configuration changes are documented and can be reverted if needed.
  3. Flexibility: Config files offer more flexibility compared to the .env file. You can define complex configuration structures, arrays, and nested values in config files, making it suitable for handling advanced configuration scenarios.
  4. Environment-specific Settings: Laravel config files support environment-specific configuration. You can have different settings for different environments (e.g., development, production, staging) and easily switch between them without modifying the .env file.
  5. Caching: Laravel allows you to cache the configuration files, which can significantly improve application performance. When using the .env file directly, caching is not possible, and each access to environment variables requires file parsing, leading to a performance overhead.
  6. Code Readability: Accessing configuration values through the config() helper function provides better code readability compared to directly accessing the .env file. It clearly indicates that you are fetching a configuration value, improving code maintainability and understanding.

Conclusion

Using Laravel config files is the recommended approach for accessing .env variables in your application.

By using the config() helper function, you can ensure predictable behavior and avoid issues with empty values when caching configurations. This also allows you to better organize your configuration, support configuring different environments and to improve performance.

Now go ahead and configure your own applications with any settings you might need. Happy coding!

Johan van den Broek

Johan is the creator of laracoding.com. As a child, he began tinkering with various programming languages, many of which have been long forgotten today. Currently, he works exclusively with PHP and Laravel, and his passion for programming remains to this day.

Leave a Reply

Your email address will not be published. Required fields are marked *

Recent Posts