Skip to content
Tutorials Center
My learning

Topics

Lesson 12 of 67 ยท Routing and Controllers

The Service Container and Dependency Injection

Understand the Laravel service container: automatic resolution, bind and singleton, interface bindings, contextual binding and tagging, with a runnable autowiring container.

In the last few lessons you wrote controllers that simply asked for what they needed: a Request, a service, a model. Nobody wrote new PostController(...). Something built those objects and handed them over. That something is the service container, the heart of Laravel. It is a registry that knows how to create objects, and a factory that can build them recursively by reading type hints.

Dependency injection (DI) means a class receives its collaborators instead of creating them. It makes code easier to test and to change: swap a real payment gateway for a fake in a test, or switch the mailer in production, without touching the classes that use them. If the idea is new, read dependency injection in PHP first; this lesson shows how Laravel's container automates it, and then you will build a small container yourself.

Laravel snippets are read-only. The runnable examples are plain-PHP stand-ins that copy the container's behavior; the real one (Illuminate\Container\Container) has many more features and edge cases.

Automatic resolution

The container needs no configuration for a concrete class whose constructor asks for other concrete classes. It reads each type hint with reflection and builds the whole tree:

PHP
class Mailer {}

class WelcomeService
{
    public function __construct(private Mailer $mailer) {}
}

class SignupController
{
    public function __construct(private WelcomeService $welcome) {}
}

$controller = app(SignupController::class);   // builds Mailer, then WelcomeService, then the controller

Laravel does the same for controllers, middleware, jobs, event listeners and Blade components. You can ask for an object yourself with app(Foo::class) or resolve(Foo::class), but in application code prefer type-hinting in a constructor or method. Asking the container directly from inside a class (the "service locator" style) hides dependencies.

Binding

Automatic resolution cannot guess in two cases: when the type hint is an interface (which cannot be instantiated), and when construction needs a value such as an API key. You tell the container what to do with a binding. Do this in a service provider, in its register() method:

PHP
use App\Contracts\PaymentGateway;
use App\Services\StripeGateway;
use Illuminate\Contracts\Foundation\Application;

public function register(): void
{
    // Interface to implementation
    $this->app->bind(PaymentGateway::class, StripeGateway::class);

    // A closure for custom construction
    $this->app->bind(StripeGateway::class, function (Application $app) {
        return new StripeGateway(config('services.stripe.secret'));
    });
}

After this, any class that type-hints PaymentGateway gets a StripeGateway. Changing providers later is a one-line edit, and a test can bind a fake instead.

Singletons and instances

bind creates a new object each time it is resolved. If everyone should share one object, say so:

PHP
$this->app->singleton(ExchangeRates::class, fn () => new ExchangeRates(config('services.rates.url')));

$this->app->instance(Clock::class, new FixedClock('2026-01-01'));   // an object you already built

scoped() is a middle path: one instance for the lifetime of a request (or one queued job), which matters in long-running servers such as Octane where a plain singleton would survive across requests. Be careful with singletons that hold request-specific data: shared state is a classic source of bugs.

Binding in tests

Because everything resolves through the container, tests can replace parts of the system:

PHP
$this->app->instance(PaymentGateway::class, new FakePaymentGateway());
// or let Laravel build a Mockery double:
$this->mock(PaymentGateway::class, fn ($mock) => $mock->shouldReceive('charge')->andReturn(true));

Faking and mocking builds on this.

flowchart TD
    Q["Controller asks for<br/>OrderService"] --> A{"Binding for<br/>OrderService?"}
    A -->|yes| B["Run the binding"]
    A -->|no| C["Read constructor<br/>type hints"]
    C --> D["Resolve each dependency<br/>the same way"]
    D --> E["new OrderService(...)"]
    B --> F["Return object"]
    E --> F

Resolution is recursive: every dependency goes through the same decision, until classes with no dependencies are reached.

Contextual binding

Sometimes two classes need different implementations of the same interface:

PHP
use Illuminate\Contracts\Filesystem\Filesystem;
use Illuminate\Support\Facades\Storage;

$this->app->when(PhotoController::class)
    ->needs(Filesystem::class)
    ->give(fn () => Storage::disk('public'));

$this->app->when(BackupJob::class)
    ->needs(Filesystem::class)
    ->give(fn () => Storage::disk('s3'));

Reading it aloud works: "when PhotoController needs a Filesystem, give it the public disk". The same API can bind plain values with ->needs('$perPage')->give(25).

Tagging

If you have several implementations of something and want them all, tag them and ask for the group:

PHP
$this->app->tag([CpuReport::class, MemoryReport::class, DiskReport::class], 'reports');

$this->app->bind(ReportRunner::class, function (Application $app) {
    return new ReportRunner($app->tagged('reports'));
});

tagged('reports') yields one resolved object per class. New report classes join the system by being tagged, and ReportRunner never changes.

Provider rules of thumb

register() should only bind things into the container; do not resolve other services there, because they may not be registered yet. Anything that needs the whole application ready belongs in boot(). The next lesson covers the difference in detail.

A container in plain PHP

This container supports bind, singleton, instance and automatic resolution through reflection. It reports the same kinds of failure that Laravel does: an interface with no binding, an unresolvable primitive, and a circular dependency. Objects are compared with === to show the difference between bind and singleton.

PHP A tiny autowiring container

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Each message above has a counterpart in Laravel: "Target [X] is not instantiable", "Unresolvable dependency resolving [...]" and a circular dependency exception. Reading the failure and knowing which of the three it is will solve most container errors you meet.

Contextual binding and tagging in plain PHP

Now the two advanced features. A contextual binding is keyed by the class being built, so the container needs to remember who is asking. Tags are just named lists of abstracts that are resolved on demand.

PHP Contextual binding and tags

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Only BackupJob got S3; every other consumer fell back to the default binding. In Laravel, the same when()->needs()->give() reads almost word for word.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. When does the Laravel container need an explicit binding?

    Concrete classes with class-typed dependencies are built automatically. Interfaces cannot be instantiated and primitives such as API keys cannot be inferred, so those need bindings.
  2. 2. What is the difference between bind() and singleton()?

    A bound abstract is built each time it is resolved. A singleton is built once and the same instance is returned afterwards.
  3. 3. Why should register() in a service provider avoid resolving other services?

    All providers run register() before any boot(). Resolving something inside register() may fail because its binding does not exist yet. Use boot() for work that needs other services.
  4. 4. What does $this->app->when(BackupJob::class)->needs(Filesystem::class)->give(...) achieve?

    Contextual binding answers "when this class needs this abstraction, supply that". Other classes keep the default binding.

Summary

  • The service container builds objects and their dependencies recursively by reading constructor type hints.
  • Bind interfaces to implementations, and give custom construction logic as a closure, inside a provider's register() method.
  • bind() makes a new object each time; singleton() shares one; scoped() shares one per request or job; instance() registers an existing object.
  • Contextual binding gives specific classes specific implementations; tagging collects related implementations.
  • Tests replace services by rebinding them in the container.

Next: Service Providers, Facades and Contracts