Laravel Service Container

Print Print
Reading time 1:9

The service container is a tool for managing class dependencies and performing dependency injection throughout a Laravel application. It is responsible for resolving classes automatically and keeping track of how they should be constructed, which allows large parts of the framework to be swapped out or tested in isolation.

Automatic Resolution

For most classes with no interface dependencies, the container needs no explicit configuration. If a controller's constructor type-hints a class, Laravel will automatically instantiate it (and recursively resolve its own dependencies) when the controller is created.

Constructor injection

class PodcastController extends Controller
{
    public function __construct(protected AudioProcessor $processor)
    {
    }
}

Binding Interfaces

When a class depends on an interface rather than a concrete implementation, the container needs to be told which implementation to provide. This is usually done in a service provider's register method.

Binding example

$this->app->bind(PaymentGateway::class, StripePaymentGateway::class);

Singletons

The singleton method binds a class or interface so that it is only resolved once, with the same instance returned on every subsequent request from the container - useful for objects that are expensive to construct or that hold shared state.

Service Providers

Service providers are the central place where the container is configured. Every Laravel application boots a set of service providers, defined in the application's configuration, which register bindings and perform other setup before the application handles a request.

By: Tomas Silny
Edited: 2026-08-13 03:31:20