简体   繁体   中英

Accessing new Laravel config files during request

I have a scenario where Laravel config files are created and accessed during the same incoming request. However, when accessing the new stored config file's values, config() is unable to access the file's keys/values.

Here is an example scenario:


public function create(Request $request)
{
    $settings = ['foo' => 'bar'];
    // Store the config.
    Storage::disk('config')->put("settings.php", '<?php return ' . var_export($settings, true) . ';');
    // Results in an error, value not found.
    $config_value = config('settings.foo'); 
}

Is there a way to re-register Laravel config files during a runtime?

Saving contents to the php file config/settings.php is (obviously) not the best way to do it.

Either save the config to a database, or simply use the config() helper to assign the values like this:

class MyConfigProvider extends ServiceProvider
{
    public function boot() {
        $this->app->booted(function () {
            // This will set the config setting `config/settings.php['app_name']` at runtime:
            config([
                'settings.app_name' => 'My App Name'
            ]);
        });
    }
}

Then, make sure to load this service provider as early in the stack as possible in your config/app.php['providers'] array. Basically it overwrites any predefined config that you have set in config/settings.php . You can even retrieve values here from the request object or your database.

Yes there is a method for that:

config()->set('settings.foo', $somethingNew);

and then you can read it normally with:

$config_value = config('settings.foo'); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM