Edit a config variable of a custom module in controller Is it possible to edit/create a config variable of a module in a controller created in the same module?

For example:
module_name/src/Controller/MyController.php: 

class MyController extends ControllerBase {

    public function x($y) {
        $config = \Drupal::config('module_name.settings');
        $config-&gt;set('var1', $y)-&gt;save();
    }
}


Update:

module_name.module: 

function module_name_page_attachments(array &amp;$page) {
  $config = \Drupal::config('module_name.settings');
  var_dump($config-&gt;get('var1'));
}


module_name/config/install/module_name.settings.yml: 

var1: 0


module_name/src/Form/moduleNameSettings.php:

class moduleNameSettings extends ConfigFormBase {

    protected function getEditableConfigNames() {
        return [
            'module_name.settings',
        ];
    }


    public function submitForm(array &amp;$form, FormStateInterface $form_state) {
        parent::submitForm($form, $form_state);
        $config = \Drupal::config('module_name.settings');

        $this-&gt;config('module_name.settings')
            -&gt;set('var1', $config-&gt;get('var1'))
            -&gt;save();
    }
With the ConfigFormBase, you need to implement the editableConfigNames() method.  E.g. 

  /**
   * {@inheritdoc}
   */
  protected function getEditableConfigNames() {
    return [
      'example.settings',
    ];
  }


In general, you need to get the editable version of the config file to change it.  ConfigFormBase (well actually, ConfigFormBaseTraits) will only return the editable config is you implement the above method.

For reference, here's how you could do this without the ConfForm logic.

$config = \Drupal::service('config.factory')-&gt;getEditable('example.settings');
$config-&gt;set('message', 'Hi')-&gt;save();


See the documents for details.

Since you are expanding ConfigFormBase, you should be able to use:

$config = $this-&gt;configFactory()-&gt;getEditable('example.settings');


To get the editable version.