Laravel interview question · Most asked

What is the service container, and how does dependency injection work in Laravel?

Summary

The service container is Laravel's dependency-injection container: it knows how to build objects and their dependencies. When a controller, job or listener type-hints a class or interface, the container resolves it automatically.

Longer Answer

For concrete classes with resolvable constructor arguments, the container uses reflection to build them with zero configuration ("auto-wiring"). For interfaces, or classes that need configuration, you register a binding in a service provider:

  • bind creates a new instance every time it is resolved.
  • singleton creates it once per application lifetime (per request in PHP-FPM, per worker under Octane).
  • scoped creates it once per request or job, which matters for long-lived workers.
  • Contextual binding (when(...)->needs(...)->give(...)) chooses an implementation per consumer.

Injection works in constructors and in controller methods, route closures, job handle methods, and anywhere Laravel calls your code through the container. Depending on interfaces and binding implementations in one place is what makes code testable: tests swap the binding for a fake.

Code Example

// AppServiceProvider::register()
$this->app->singleton(PaymentGateway::class, fn ($app) => new StripeGateway(config('services.stripe.secret')));

// Anywhere the container builds the class, the dependency is injected.
class CheckoutController
{
    public function __construct(private PaymentGateway $payments) {}
}

Key Points

  • Auto-wiring via reflection for concrete classes.
  • bind vs singleton vs scoped.
  • Bind interfaces to implementations in a service provider.
  • Swap bindings in tests.

Explanation

What interviewers look for

Understanding of auto-wiring and binding lifetimes. A strong answer explains why singletons holding request state are dangerous under Octane and queue workers.

Follow-up questions

  • When would you use contextual binding?
  • How do you replace a binding in a test?

More most-asked Laravel questions

← All Laravel questions