2

Suppose I have a price_list option that I set in to null in the app.php file:

'price_list' => null,

price_list should be set based on some conditions when my app is run. for example if logged in user has administrator role then I should fetch appropriate value from a price_list table:

if (Some Condition){
     $pricelist  = fetch from price_list table
     Config::set('price_list' ,$price_list);
}

So here, I found that to do that I should use a service provider and then do all those functionalities as mentioned in this Answer. But I do not know which approach is right to use boot or register method and singleton or bind method?

Alexey Mezenin
  • 158,981
  • 26
  • 290
  • 279
Ahmad Badpey
  • 6,348
  • 16
  • 93
  • 159

2 Answers2

2

As mentioned in the documentation, you should never attempt to register any event listeners, routes, or any other piece of functionality within the register method.
Otherwise, the boot fits exactly your needs, which is called after all other service providers have been registered.
so you can do something like:

if (\Auth::user()->isAdmin()) { //you can make the function in the model, here just an example
    config()->set('price_list', 'blablabla);
}
Gothiquo
  • 841
  • 1
  • 8
  • 31
0

Do that in the boot() method. From the docs:

Within the register method, you should only bind things into the service container.

Also, you don't need to use bind() or singleton() methods for that. Just do this:

public function boot()
{
    config([price_list' => $price_list]);
}
Alexey Mezenin
  • 158,981
  • 26
  • 290
  • 279
  • May I have similar need to define new options in Continued development.Is it necessary to define separate serviceProvider for each them? – Ahmad Badpey Feb 07 '18 at 08:10
  • @A.B.Developer if you're going to override more configs in the future, it's a good idea to define a separate service provider for this (one provider for all `config()` clauses). – Alexey Mezenin Feb 07 '18 at 08:12