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:
bindcreates a new instance every time it is resolved.singletoncreates it once per application lifetime (per request in PHP-FPM, per worker under Octane).scopedcreates 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.
bindvssingletonvsscoped.- 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
- How do you validate requests in Laravel? Why use Form Requests?
- How do queues work in Laravel?
- How do database transactions work in Laravel, and what pitfalls should you know?
- Which Artisan commands would you run when deploying Laravel to production, and why?
- Gates or policies: how does authorization work in Laravel?
- What is the N+1 query problem in Eloquent and how do you prevent it?
- What is mass assignment, and how do $fillable and $guarded protect against it?
- A Laravel endpoint is slow. How do you find and fix the cause?