Creating Custom Config File in Laravel is an important part of developing flexible web applications. Laravel makes it easy to manage configurations using config files, which are all stored in the config directory.
With Laravel, you can create custom config files to store values according to your application’s requirements and access them easily using the config() helper. Using config files allows you to manage global values efficiently, and Laravel can cache these values to improve performance.
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 services which includes login too.
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.
<?php
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:
GOOGLE_API_TOKEN=**********************
Using Custom Config File In Laravel
We will use config helper to get value from our custom config file.
<?php
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.
Conclusion
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.
To explore creating your own command-line tools in Laravel, take a look at Laravel Custom Artisan Command Example. This tutorial walks you through building custom artisan commands that make handling routine tasks in Laravel faster and easier.