Only Use Env() In Config Files

Paulund - May 23 - - Dev Community

When working with Laravel you may find yourself needing to access environment variables in your configuration files. In this article we're going to look at how you can access these environment variables using the env() helper function.

We will use the environment variables to have different settings for our application on different machines for example you might want different settings for the app in development and production.

Laravel provides a helper function called env() that allows you to access environment variables in your application. This function takes two arguments the first is the name of the environment variable and the second is the default value if the environment variable is not set.

This will allow you to do things in your application like this:

if(env('APP_DEBUG', false) === true) {
    // Do something
}
Enter fullscreen mode Exit fullscreen mode

But there is a problem with the above code, this will work in development but there will be a problem in production.

In most laravel production applications we use the command php artisan config:cache to cache the configuration files. This will speed up the application as it doesn't need to read the configuration files on every request.

But the problem with the above code is that the env() function will not work when the configuration files are cached. This is because the env() function is a helper function and it will not be executed when the configuration files are cached. You will get a null response from the env() function when the configuration files are cached.

So how do we fix this? The solution is to use the config() function instead of the env() function. The config() function will work when the configuration files are cached.

The config() function works in the same way as the env() function but it will work when the configuration files are cached.

So the above code can be changed to:

if(config('app.debug', false) === true) {
    // Do something
}
Enter fullscreen mode Exit fullscreen mode

This will work in both development and production environments.

In your config files you can use the env() function as this will be used to build the configuration cache like this.

'debug' => env('APP_DEBUG', false),
Enter fullscreen mode Exit fullscreen mode

You can read more about production optimization in the Laravel documentation.

Now you know how to use the env() function in your configuration files in Laravel. This will help you to have different settings for your application on different machines and environments.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .