Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

laravel
communitycreator

How to use the config() method in Laravel

Chinweuba Elijah Azubuike

Overview

Setting configuration values in your config files can be very useful when trying to apply settings in an application, such as when you want to set the timezone in your basic config file.

In this shot, I will teach you how to set configuration values from your config directory with the config() method.

What is the config method?

The config method allows your application to get or set values in all files that are in the config directory.

How to use the config() method to set values

To set values from files in the config directory, we will use the config() method.

In the config() method, we use dot notation to get the value we want. The first parameter we use is the name of the file without .php, and then we drill down like we are trying to access values from an array until we get the specific value we are looking for. The second parameter we pass to the config() method is the new value.

Syntax

config('social.facebook.url', 'http://example.com');

Parameters

The config() method receives the file and the array/key to be accessed in a dot notation format, as seen in the example as the first parameter and the new value as the second parameter.

Example

In our config directory, we create a file called socialhandele.php, with its content as shown below:

<?PHP 
return [ 
'facebook' => [ 
'url' => 'https://www.facebook.com/scotchdevelopment', 
'username' =>'scotchdevelopment' ], 

'twitter' => [ 
'url' => 'https://twitter.com/scotch_io',
 'username' => 'scotch_io' ] ];

 

Example explained

To set or change the Facebook URL in the socialhandle.php file from your controller, we would use the following code:

$fbUrl = config('socailhandle.facebook.url'=>'https://www.facebook.com/chinweubaelijah');

Notice that we do not add the .php extension when we use the socialhandle file. We drill down from the socialhandle file to the facebook array, down to the url key, then pass the new value.

RELATED TAGS

laravel
communitycreator

CONTRIBUTOR

Chinweuba Elijah Azubuike
RELATED COURSES

View all Courses

Keep Exploring