Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reassign or refresh a singleton in Laravel 5

I have a Provider and in its register method I defined a singleton like this,

$this->app->singleton('my.custom.singleton', function ($app) {
    $config_value = $app->make($this->config('key'));
    return new MyClass($config_value);
});

as you see, I get a config value and put it as a parameter in my class.

In another place of my project, I change the value of config('key') using code:

Config:set('key',$my_changed_value);

and I call a method of MyClass that uses the parameter that I send it to the class in my provider above.

But MyClass not use the new value of config('key'). I think it happens because the singleton has been defined with the default value of config.

I think it will be ok if I could redefine the singleton after assigning new values of config.

Or is there any solution for my issue? Am I wrong? What can I do to use the new value in MyClass?

like image 685
Behnam Azimi Avatar asked Jun 10 '18 17:06

Behnam Azimi


Video Answer


1 Answers

Just assign null to it and it will be created from scratch on the next call

app()->instance(PaymentServiceContract::class, null);
like image 62
Yevgeniy Afanasyev Avatar answered Oct 11 '22 12:10

Yevgeniy Afanasyev