Behnam Azimi
Behnam Azimi

Reputation: 2488

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?

Upvotes: 8

Views: 2699

Answers (2)

Yevgeniy Afanasyev
Yevgeniy Afanasyev

Reputation: 41360

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

app()->instance(PaymentServiceContract::class, null);

Upvotes: 6

webdevtr
webdevtr

Reputation: 480

It might be related config cache, Do you use config cache ?

Can you try again after clear cache

php artisan config:clear

Upvotes: -2

Related Questions