Laravel: cascading custom configuration path image

Laravel: cascading custom configuration path

 

For those times when you want to host configuration files in a custom path but also want changes "cascade" over the original files; just like the environment ones.

So we need to register a configuration namespace with the resources path and a callback to merge settings when the configuration group, for the given namespace, is loaded the first time.

Config::addNamespace('myapp', '/path/to/my/custom/config/folder');

Config::afterLoading('myapp', function($namespace, $group, $items)
{
    // Prevent to load base settings if they have been previously loaded
    $default = isset(Config::getItems()['*::'.$group])
            ? Config::getItems()['*::'.$group]
            : Config::getLoader()->load(App::environment(), $group) ;

    return array_replace_recursive($default, $items);
});

So if, for example, we have:

// app/config/app.php
return [
    ...
    'timezone'  => 'UTC',
    'locale'    => 'en',
    ...
];

// somewhere/far/away/config/app.php
return [
    'timezone'  => 'Europe/Madrid',
];

And we access those properties, obtain:

Config::get('myapp::app.timezone'); // 'Europe/Madrid'
Config::get('myapp::app.locale');   // 'en'

Note that this does not prevent to use specific environment settings.

You can take a look:

  • Illuminate\Config\Repository
  • Illuminate\Config\FileLoader

 

comments powered by Disqus