Laravel dynamic config settings

后端 未结 8 1549
抹茶落季
抹茶落季 2020-12-14 07:13

I\'m using a package within my project and it stores a setting inside config/packagename

I would like to dynamically change this value inside the config

8条回答
  •  既然无缘
    2020-12-14 07:24

    If you want to actually edit the config files (either config/packagename.php or .env) then you may follow matthiku's answer.

    However, if I were you, I guess I'd rather want to configure this 3rd party package based on some value defined at runtime, instead of modifying any file (which by the way won't take effect until the next request, when the env values are read again).

    So, in my opinion the cleanest way to do this is:

    • store your desired value in the config data:

      config(['packagename.view_id' => Auth::user()->id]);

    • However, you may notice this probably won't work: the service provider which provides the service you need is often registered before the request is processed, that is, before your config change takes place. So you are still getting the service with old values config.

    • So, how could you have the service provider be called only when needed and not before (that is, after setting the new config value)? You could make it a deferred provider. Following your example of "spatie laravel-analytics", replace in config/app.php this line:

      Spatie\Analytics\AnalyticsServiceProvider::class

      with this one:

      App\Providers\AnalyticsDeferredServiceProvider::class

      and finally create the App\Providers\AnalyticsDeferredServiceProvider class, with:

    :

    This way you can have the provider read the config values when you are about to instantiate the service, after you set any runtime config values.

提交回复
热议问题