How to access config file values in Laravel using config()?

Overview

Getting configuration values from your config files can be very useful when applying a setting in your application. For example, it helps us get the Timezone from our basicconfig file. This shot will teach us to get configuration values from our config directory using the config() method.

What is the config() method?

The config method allows our application to access values from all files in the config directory.

How to use the config() method

We use the config() method to get values from files in the config directory. We use the dot notation to get the value we want. The first parameter we use is the file’s name without the .php extension. Then, we drill down like we are trying to access values from an array till we get the specific value we are looking for.

Syntax

config()

Parameters

To get values, the config() method receives the file and the array/key to be accessed in a dot notation format.

Code example

We create a file called socialhandle.php with its content in our config directory. We also create a function in the app/Http/Controllers/yourController.php file that will call the config method in line 17 when the code is executed. You can see the result in the Output tab on executing the code below.

<?php

use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/', function () {
    return view('output');
});
Code example for the config() method

Explanation

To get the Facebook URL from the socialhandle.php file from our controller, we do the following:

$fbUrl = config('socialhandle.facebook.url'); echo $fbUrl;

Notice that we do not add the .php extension when using the socialhandle file. We drill from the socialhandle file to the facebook array down to the url key.

Output

When you execute the code above you see the following output as it is the url stored in the facebook array.
https://www.facebook.com/scotchdevelopment

Free Resources