php - Laravel service provider choose which class to inject

one text

Solution:

In you ServiceProvider's register method:

 public function register()
 {
    $this->app()->singleton()->(YOUR_CONTRACT::class, function(){
        if(request('certain_field')){
          return new CONCRETE_IMPLEMENTATION_1::class;
        }
        else{
          return new CONCRETE_IMPLEMENTATION_2::class;
        }
    });
 }

In your controller you would inject your contract/interface like so, e.g through method injection:

public function someMethod(YOUR_CONTACT::class $concreteImplementation){
  // it will be correct implementation of your contract/interface
}

Source