Imagine you want to define some variables that can be accessed from anywhere in your laravel project. To achieve that, the best way will be to take advantage of laravel’s configuration file.

Creating a Configuration File

First, you need to create a file inside the config folder at the root of the laravel project – config/global.php. Inside the file, you need to return an array.

$my_config = array();
return $my_config;

 

Defining Variables

Once you have the configuration file ready, you can then define your global variables as key-value pairs inside the array. Remember, The array can also be multi-dimensional.

$my_config = array(
    'site_name' => "WickeDev",
    'site_desc' => "A blog for developers",
    'contact' => array (
        'email' => 'john.doe@website.com',
        'phone' => '+1-906-123-4567',
    )
);
return $my_config; 

 

Accessing Variables

Now, you can access the variables using “dot” syntax, including the configuration file name without the extension – php. You can do it in 2 ways.

1. Using the “Config” facade

Laravel has a built-in facade called Config. You can use the facade’s static get() method to access the variables like below.

$site_name = Config::get('global.site_name');
$email = Config::get('global.contact.email');

 

2. Using the “config()” function

The config() function works like the Config facade, just like below.

$site_name = config('global.site_name'); 
$email = config('global.contact.email');