How to get values from config files in Laravel with Config facade

Overview

Retrieving configuration values from your config files can be very useful when you want to apply a setting in your application. For example, if you want to get the Timezone from your basic config file.

In this shot, I will teach you how to use the Config facade to get configuration values from your config directory.

What is the Config facade?

The Config facade allows your application to get access to values from all of the files that are in the config directory.

How to use the Config facade to get values

To get values from files in the config directory, we can use the get() method on the Config facade.

In the get() method, we use dot notation to get the value we want. The first parameter is the name of the file name without .php. We drill down like we are trying to access values from an array until we get the specific value we are looking for.

Example

In our config directory, we create a file called socialhandele.php, with its content as shown below:

<?php
return [
    'facebook' => [
        'url' => 'https://www.facebook.com/scotchdevelopment',
        'username' => 'scotchdevelopment'
    ],
    'twitter' => [
        'url' => 'https://twitter.com/scotch_io',
        'username' => 'scotch_io'
    ]
];

Example explained

To get the Facebook URL from the socialhandle.php file from the controller, we can use the following code:

$fbUrl = Config::get('socailhandle.facebook.url');
echo $fbUrl;

Notice how we do not add the .php extension when we call the socialhandle file.

We drill down from the socialhandle file to the facebook array, down to the url key.

Output

https://www.facebook.com/scotchdevelopment