What are Laravel 8 Config Files & How to fetch value?

Configuration files allow you to configure things like the database connection information, your mail server information, and also other core configuration values. Laravel 8 Config Files come under the config directory of a Laravel application.

Configuration file may vary based on the development server and the use the .env variables to fetch the configuration dynamically. For example: your database configuration can be different on local, staging or on production server. This depends on what value is inside your .env file for each environment. As discussed before, since the .env file variables are based on the development server, so does the config file data.

If you open config/database.php file it might look like following:

Note the following line:

# if DB_CONNECTION variable is defined in .env
# file than it uses that value otherwise it uses mysql
# as default value 
env('DB_CONNECTION', 'mysql');​

How to fetch configurations in Laravel 8?

We now know that all configuration files come under the config directory in a Laravel project. The file name is used as a key and the variables defined in the file, are accessed using a dot notation. For example, as shown below.

# fetch database default config
$databaseDefaultKeyValue = config('database.default');

# fetch current app timezone
$timezone = config('app.timezone', 'Asia/Dubai');

You can also override these values as shown in the example below.

# override what is defined in config/app.php => timezone key
config(['app.timezone' => 'America/Chicago']);​

How to cache Laravel 8 configurations?

You can boost your Laravel app by storing cached configuration by using the following command:

# create cache copy of configurations
php artisan config:cache​

How to hide errors in production environment?

A debug option in your config/app.php configuration file can determine the amount of information about an error which should be displayed to a user. By default, this option is set to respect the value of the APP_DEBUG environment variable, which is stored in your .env file.

As per Laravel documentation, local development servers, should set the APP_DEBUG environment variable to true. While on the production environment, this value should always be false. If the variable is set to true in production, there is a risk to expose configuration data to application’s users.

Leave a Comment