When you are writing a Laravel package, usually you need a config file.
Also, we will publish the config file in the “boot” method of the service provider.
Then, in the “register” method you can get the configuration and use it when you create the instance of “Facade”.

Let’s see a typical config file:

<?php

return [
  'myKey" => 'myvalue",
  'myOtherKey" => env('MYVALUE_FROM_ENV', 'default')
];

Usually, we can use both static and dynamic values for our keys. Regarding dynamic values, you know that we can use only the environment values because any database access is denied in this context.

So, I use the following workaround very easy to implement. First of all, I add a new key in my configuration file, for example, “config_controller”.

<?php

return [
  'config_controller' => '',
  'myKey" => 'myvalue",
  'myKey" => 'myvalue",
  'myOtherKey" => env('MYVALUE_FROM_ENV', 'default');
];

This new key will be a class which we can use to get either all or any. In the “register” method of my service provider, I’ll check this new key. If it exists, then I will use that controller to change my configuration.





/**
 * Register the service provider.
 *
 * @return void
 */
public function register()
{
  App::bind('namespace.facade',
    function () {
      $config = config('myconfig');
      if ( ! $config ) {
        throw new \RunTimeException('MyService configuration not found. Please run `php artisan vendor:publish`');
      }
      if (!empty($config['config_controller'])) {
        $callable = $config['config_controller'];
        if (str_contains( $callable, '@')) {
          $callable = explode('@', $callable);
        }
        else {
          $callable = [$callable, 'getConfig'];
        }
        if (is_callable($callable)) {
          $config = call_user_func_array( $callable, [ $config ] );
        }
        else {
          $implode = implode( ",", $callable );
          throw new \RunTimeException( "MyService configuration {$implode} is not callable" );
        }
      }
      return new MyClass( $config );
    }
  );
}

In the configuration file you can use:

<?php

return [
  'config_controller' => App\Configuration\MyConfig::class,
  'myKey" => 'myvalue",
  'myOtherKey" => env( 'MYVALUE_FROM_ENV', 'default' );
];

or

<?php

return [
  'config_controller' => 'App\Configurations\MyConfig@myCustomMethod',
  'myKey" => 'myvalue",
  'myOtherKey" => env( 'MYVALUE_FROM_ENV', 'default' );
];

If the method name is not specified then getConfig will be used.
Let’s see a typical controller used to modify the configuration:

<?php

namespace App\Configurations;

use App\Models\MyModel;

class MyConfig 
{
  public static function getConfig( $config )
  {
    // for example, noew we can get the value from a Eloquent database model
    $config['myKey'] = MyModel::where('key', 'myKey')->first()->value();

    return $config;
  }
}

In the above code, we have modified only one key. Of course, you can change the whole configuration file.