Laravel dynamic config settings

后端 未结 8 1550
抹茶落季
抹茶落季 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:25

    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.

提交回复
热议问题