Search code examples
laravelservice-provider

Should I run database queries while binding in a Laravel Service Provider?


The following is basically what I have right now and it seems to be working. But I've found people saying that you shouldn't run database queries in the Service Provider because not everything may be registered yet. Are there potential issues with doing the config this way? And if so is there an alternative way to setup a similar situation where I grab configuration data from a database?

I was originally using a config file to bind an instance of the object I wanted

config/payment.php

'test' => array(
    'terminalid' => env('TERMINAL'),
    'secret' => env('SECRET'),
),

PaymentServiceProvider in the register method

  public function register()
  {
      $this->app->bind(Gateway::class, function ($app) {
          $gateway = new Gateway();
          return $gateway->initialize([
              config('payment.test')
          ]);
      });
  }

But I want to change this to base the configuration off a database query.

Settings table

license terminal secret
test ABC123 XXXX
demo ZYX987 XXXY

So something like this

  public function register()
  {
      $this->app->bind(Gateway::class, function ($app) {
          $setting = Setting::where("id",request()->id)->first();
          $gateway = new Gateway();
          return $gateway->initialize([
              'terminalid' => $setting->terminal,
              'secret' => $setting->secret,
          ]);
      });
  }

Solution

  • I think you can move code from register method into boot method

    public function boot() {
       $this->app->bind(Gateway::class, function ($app) {
          $setting = Setting::where("id",request()->id)->first();
          $gateway = new Gateway();
          return $gateway->initialize([
             'terminalid' => $setting->terminal,
             'secret' => $setting->secret,
          ]);
       });         
    }
    

    So, you will be sure that all needed services are registered already