Laravel Helper Function: config

November 20, 2016 —John Koster

config($key = null, $default = null)

The config helper function is a versatile function. If the supplied $key and $default value are both null, such as in the following method call:

1<?php
2 
3// Calling the `config` function without any arguments
4config();

the return value will be, by default, an instance of Illuminate\Config\Repository (more specifically, the return value will be whatever class instance is bound to the config alias within the service container). This can be used a shortcut to accessing the configuration repository (versus injecting an instance of the configuration repository or using the Config facade):

1<?php
2 
3// Using the `config` function to return an instance of
4// `Illuminate\Config\Repository` to check if a config item exists.
5if (config()->has('someKey')) {
6 // Do something if the `someKey` config item exists.
7}

#Setting Configuration Values

The config function can be used to set configuration values if the provided $key is an array, and no $default value is supplied (or the $default value supplied is null). If multiple items are passed exist in the array, all key/value pairs will added to the configuration:

1<?php
2 
3// New config items to store.
4$newConfigurationValues = [
5 'keyOne' => 'valueOne',
6 'keyTwo' => 'valueTwo',
7 'keyThree' => 'valueThree'
8];
9 
10// Store all three key/value pairs in the config.
11config($newConfigurationValues);

In the above example all three key/value pairs will be stored in the configuration separately. The following example highlights how the values are returned (by returning an instance of the configuration repository). The value returned will appear above the function call as a comment:

1<?php
2 
3// valueOne
4config()->get('keyOne');
5 
6// valueTwo
7config()->get('keyTwo');
8 
9// valueThree
10config()->Get('keyThree');

#Retrieving Configuration Values

The config function can even be used to retrieve configuration values, as long as the provided $key is not an array and not null. A $default value can be supplied that will be returned if the configuration $key does not exist. The following examples will use the $newConfigurationValues from the previous section. The value returned will appear above the function call as a comment:

1<?php
2 
3// valueOne
4config('keyOne');
5 
6// valueTwo
7config('keyTwo');
8 
9// valueThree
10config('keyThree');
11 
12// Not null
13config('nonExistent', 'Not null');

Some absolutely amazing
people

The following amazing people help support this site and my open source projects ♥️
If you're interesting in supporting my work and want to show up on this list, check out my GitHub Sponsors Profile.