Laravel dynamic config settings Laravel dynamic config settings laravel laravel

Laravel dynamic config settings


This also is a generic solution to dynamically update your .env file (respective the individual key/value pairs)

  1. Change the setting in your config/packagename like so:
return [    'view_id' => env('VIEW_ID', '118754561'),    etc...]
  1. Add an initial value into .env:

    VIEW_ID=118754561

  2. In an appropriate controller (e.g. AuthController), use the code below and call the function like this:updateDotEnv('VIEW_ID', Auth::User()->id)

    protected function updateDotEnv($key, $newValue, $delim=''){    $path = base_path('.env');    // get old value from current env    $oldValue = env($key);    // was there any change?    if ($oldValue === $newValue) {        return;    }    // rewrite file content with changed data    if (file_exists($path)) {        // replace current value with new value         file_put_contents(            $path, str_replace(                $key.'='.$delim.$oldValue.$delim,                 $key.'='.$delim.$newValue.$delim,                 file_get_contents($path)            )        );    }}

(The $delim parameter is needed if you want to make this function more generic in order to work with key=value pairs in .env where the value has to be enclosed in double quotes because they contain spaces).

Admittedly, this might not be a good solution if you have multiple users at the same time using this package in your project. So it depends on what you are using this package for.

NB: You need to make the function public of course if you plan to use it from other classes.


All configuration files of Laravel framework stored in the app/config directory.

so if we need to create custom configuration values it would be better to keep separate our custom configuration in custom file.so we need to create custom file in app/config directory.

Laravel auto read this file as a config file and will auto manage itIn this topic we are working with custom configuration in laravel and get configuration value in controller or view.

Now i am going to explain how to create a custom config file in Laravel so that we can implement dynamic feature over to this.

create a file in app/config/custom.php which have config keys and value like:-

return array(  'my_val' => 'mysinglelue',  'my_arr_val' => array('1', '2', '3'),);

Now need to get these config values in view/controller so we will use Config class get() method for this

Syntax:

echo Config::get('filename.arraykey');

where filename is the config file’s name, custom in our case, and key is the array key of the value you’re wanting to access.

In Our case it will be as:

echo Config::get('custom.my_val');

Create run time configuration in laravel :-

Configuration values which are set at run-time are will set for the current request, not be carried over to subsequent requests.

You can pass the dynamic values over here so that you can modify the config file dynamically over here using the isset() functions.

Like how the @Kundan roy as suggested using of the isset() the same condition applies here to. But this one is the alternative method that will work for the dynamic setting of the values in the config.

Config::set('custom.my_val', 'mysinglelue');

Hence by using this method you can create the dynamic config files based on the values that you need.


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:

:

<?phpnamespace App\Providers;use Spatie\Analytics\Analytics;use Spatie\Analytics\AnalyticsServiceProvider;class AnalyticsDeferredServiceProvider extends AnalyticsServiceProvider{    protected $defer = true;    public function provides()    {        return [Analytics::class];    }}

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.