Creating custom configuration file in laravel

While developing web applications configuration plays a major role. Laravel framework makes it easy to handle configurations for complex applications with config files. All configuration files for the Laravel framework are stored in the config directory.

In Laravel, you can create custom config files as per your requirements. You can also use the config() helper to access configuration values for any config file.

The main reason to use config files is it’s stored as global values and changes in those values can easily be handled with config files otherwise we need to change those values in actual files that we statically use. Laravel will also cache those values so it will impact performance positively.

In this example, we will create a new custom file for Google login.

Creating Config File

First of all, let’s create a new php file in the config directory and name it google.php. In this file, we will just store one value for this example.

    return [
        'api_token' => env('GOOGLE_API_TOKEN', 'your default value'),

Here, we just have created a file that returns an array containing an API token as a key. For the value of that key, we used the Environment variable. We have also configured the default value if an environment variable is not found.

Let’s add an environment variable to our env file. Open the .env file from a root directory and add the below line:


Using Custom Config File In Laravel

We will use config helper to get value from our custom config file.


namespace App\Http\Controllers;

class HomeController extends Controller
    public function index()
    	$googleKey = config('google.api_token');

Here, we can also get nested values using the.(dot) access modifier.


Here, We have just created a simple config file that contains only one value and retrieved it using the config helper in Laravel. In an actual application, there can be more than a few values or nested values as per the application’s requirement.