Explain Dependency Injection in Laravel. Why is it better than hard-coding class dependencies?
Last updated
Dependency Injection means a class receives its dependencies from outside (usually the constructor) instead of creating them. Laravel's Service Container autowires type-hinted dependencies.
You can bind an interface to a concrete class in a service provider, then type-hint the interface to swap implementations without editing the class.
Hard-coding (
new PaymentGateway()inside a class) couples classes permanently. DI enables decoupling, easy mocking in tests, and centralized object configuration.