Laravel - How to create custom configuration variables and access

When we develop a new application several times we need custom config variables. In this tutorial we will learn how to create new config variables and access them in the controller.

Create new config file in your project at config/common.php

<?php
// config/common.php
return [
    'noOfRecords' => 8,
];

With the help of global config helper function we can access configuration values anywhere in the application. Configuration value accessed using 'dot(.)'. Use <fileName>.<configVariable>.

To access config variable in controller

echo $recordPerPage = config('common.noOfRecords');
Output - 8

We can specify a default value and will be returned if the configuration option does not exist.


To access config variable in controller with default value

echo $applicationName = config('common.applicationName', 'Placement Question');
Output - Placement Question

Above code will return Placement Question because applicationName variable does not exist in common.php file.

Tags: Config variables, Config variable in laravel 8, Access config variable in laravel 8

Created At: 25 July, 2021

Views: 550



Social Sharing
Search