Laravel Service Container: Contextual Binding Guide | Mohamed Said       [Skip to content](#main)  [ ![](https://cdn.msaied.com/01KT78WE565VEMM3PSNQAAB0MH.png) Mohamed SaidLaravel Backend Engineer ](https://www.msaied.com/public) - [Home](https://www.msaied.com/public)
- [Projects](https://www.msaied.com/public/projects)
- [Articles](https://www.msaied.com/public/articles)
- [Certificates](https://www.msaied.com/public/certificates)
- [About](https://www.msaied.com/public#about)

           [  Contact](https://www.msaied.com/public#contact) Menu 

Menu
----

Close 

 - [HomeStart here](https://www.msaied.com/public)
- [ProjectsCase studies](https://www.msaied.com/public/projects)
- [ArticlesEngineering notes](https://www.msaied.com/public/articles)
- [CertificatesCredentials](https://www.msaied.com/public/certificates)
- [AboutHow I work](https://www.msaied.com/public#about)
- [ContactGet in touch](https://www.msaied.com/public#contact)

  [Start a conversation](https://www.msaied.com/public#contact) [WhatsApp](https://wa.me/201094619204) [Email](mailto:hello@msaied.com) 

 1. [Home](https://www.msaied.com/public)
2. /
3. [Articles](https://www.msaied.com/public/articles)
4. /
5. Contextual Binding and Method Injection in Laravel's Service Container

 Contextual Binding and Method Injection in Laravel's Service Container
=======================================================================

 Go beyond basic IoC: learn how contextual binding, tagged services, and method injection let you wire complex dependency graphs cleanly without a single service locator call.

 ![](https://cdn.msaied.com/01M22N44A70A5MC2S599JP0MPH.webp) [Mohamed Said](https://www.msaied.com/public#person) Published 10 Aug 2026 · Updated 10 Aug 2026 · 3 min read

ShareCopy linkCopied

 ![Contextual Binding and Method Injection in Laravel's Service Container](https://cdn.msaied.com/531/d6ae9a61db2751ec26ea4113b9885f44.png) 

  On this page +1. [Why the Basics Are Not Enough](#why-the-basics-are-not-enough)
2. [Contextual Binding](#contextual-binding)
3. [Passing Primitive Values](#passing-primitive-values)
4. [Tagging Services](#tagging-services)
5. [Method Injection](#method-injection)
6. [Invokable Classes](#invokable-classes)
7. [Practical Patterns](#practical-patterns)
8. [Takeaways](#takeaways)

 Why the Basics Are Not Enough
-----------------------------

Most Laravel developers know `app()->bind()` and constructor injection. That covers 80 % of cases. The remaining 20 % — multiple implementations of the same interface, environment-specific drivers, or controller methods that need one-off dependencies — is where the container's advanced features earn their keep.

---

Contextual Binding
------------------

Contextual binding answers the question: *"Which implementation should this specific class receive?"*

```php
// AppServiceProvider::register()
$this->app
    ->when(OrderExporter::class)
    ->needs(StorageContract::class)
    ->give(S3Storage::class);

$this->app
    ->when(ReportArchiver::class)
    ->needs(StorageContract::class)
    ->give(LocalStorage::class);

```

Both `OrderExporter` and `ReportArchiver` type-hint `StorageContract`. The container resolves each to a different concrete without touching either class. No factory, no `if` branch, no service locator.

### Passing Primitive Values

Contextual binding also handles scalar config values:

```php
$this->app
    ->when(SlackNotifier::class)
    ->needs('$webhookUrl')
    ->give(fn () => config('services.slack.webhook'));

```

The `$webhookUrl` constructor parameter is injected automatically. Combine this with `giveConfig()` (available since Laravel 10) for a one-liner:

```php
$this->app
    ->when(SlackNotifier::class)
    ->needs('$webhookUrl')
    ->giveConfig('services.slack.webhook');

```

---

Tagging Services
----------------

When you need *all* implementations of a concept — think report generators, payment gateways, or notification channels — tagging is the right tool.

```php
// Register
$this->app->bind(PdfReport::class);
$this->app->bind(CsvReport::class);
$this->app->bind(XlsxReport::class);

$this->app->tag(
    [PdfReport::class, CsvReport::class, XlsxReport::class],
    'reports'
);

```

```php
// Consume
class ReportDispatcher
{
    public function __construct(
        /** @var ReportContract[] */
        private readonly iterable $reports,
    ) {}

    public static function register(Application $app): void
    {
        $app->bind(self::class, fn ($app) => new self(
            $app->tagged('reports')
        ));
    }

    public function dispatch(string $format, array $data): void
    {
        foreach ($this->reports as $report) {
            if ($report->supports($format)) {
                $report->generate($data);
                return;
            }
        }
        throw new UnsupportedFormatException($format);
    }
}

```

`$app->tagged()` returns a lazy `TaggedIterator` — nothing is instantiated until the loop runs.

---

Method Injection
----------------

Constructor injection is the default, but the container can also inject into arbitrary methods. This is useful for controller actions, console commands, or one-off invokables where you don't want to pollute the constructor.

```php
class GenerateMonthlyReport
{
    public function handle(
        Request $request,
        ReportDispatcher $dispatcher, // injected by container
        string $format = 'pdf',
    ): Response {
        $dispatcher->dispatch($format, $request->validated());
        return response()->noContent();
    }
}

// Resolve and call anywhere:
$result = app()->call(
    [app(GenerateMonthlyReport::class), 'handle'],
    ['format' => 'csv'] // override primitives
);

```

`app()->call()` merges your explicit parameters with whatever the container can resolve. This is exactly how Laravel's route model binding and controller dispatch work internally.

### Invokable Classes

```php
class SendWelcomeEmail
{
    public function __invoke(Mailer $mailer, User $user): void
    {
        $mailer->to($user)->send(new WelcomeMail($user));
    }
}

app()->call(SendWelcomeEmail::class, ['user' => $user]);

```

The container resolves `Mailer` from the IoC graph; you supply `$user` explicitly.

---

Practical Patterns
------------------

- **Feature flags per tenant**: use contextual binding to swap a `PricingStrategy` based on the resolved tenant inside a `when()` closure.
- **Test doubles without mocking frameworks**: bind a fake in `setUp()` using `$this->app->instance(Contract::class, new FakeImpl())` — no Mockery needed for simple cases.
- **Deferred providers**: wrap tagged registrations in a `DeferrableProvider` so the entire driver set is only loaded when first requested.

---

Takeaways
---------

- Contextual binding eliminates factory conditionals by moving the "which implementation" decision into the container.
- `giveConfig()` is the cleanest way to inject scalar config into a single class.
- Tagged services + `tagged()` give you a zero-cost open/closed extension point.
- `app()->call()` enables method injection anywhere, not just in controllers.
- Combine these features in a service provider, not scattered across the codebase.

- [laravel](https://www.msaied.com/public/articles?search=laravel)
- [service-container](https://www.msaied.com/public/articles?search=service-container)
- [dependency-injection](https://www.msaied.com/public/articles?search=dependency-injection)
- [architecture](https://www.msaied.com/public/articles?search=architecture)

 Frequently asked questions 
---------------------------

  When should I use contextual binding instead of a factory class?Use contextual binding when the choice of implementation depends solely on which class is being constructed. A factory is better when the decision requires runtime data (e.g., user input or a database value) that isn't available at container build time.

   Does app()-&gt;call() work with static methods or closures?Yes. app()-&gt;call() accepts any PHP callable: a \[object, 'method'\] array, a closure, a 'Class@method' string, or an invokable class name. The container injects type-hinted parameters for all forms.

   Are tagged services instantiated eagerly when the tag is registered?No. app()-&gt;tagged() returns a lazy TaggedIterator. Concrete classes are only instantiated when you iterate over the result, so registering many tagged drivers has no upfront cost.

   ![Mohamed Said](https://cdn.msaied.com/01M22N44A70A5MC2S599JP0MPH.webp)About the author
----------------

[Mohamed Said](https://www.msaied.com/public#person)Senior Backend Engineer specializing in Laravel, scalable SaaS platforms, APIs, and cloud infrastructure. I build secure, high-performance web applications that help businesses grow.

[About](https://www.msaied.com/public#about) [GitHub ↗](https://github.com/EG-Mohamed) [LinkedIn ↗](https://www.linkedin.com/in/msaiedm/) [WhatsApp ↗](https://wa.me/201094619204) [Email Address ↗](mailto:hello@msaied.com) [My CV ↗](https://drive.google.com/file/u/0/d/1MF20IPRJyzfy32mhEutjL5EpSls0w2Q8/view)  

   [Previous articleContextual Binding and Method Injection in Laravel's Service Container](https://www.msaied.com/public/articles/contextual-binding-and-method-injection-in-laravels-service-container-1) [Next articlePostgreSQL JSONB in Laravel: Indexing, Querying, and Casting Without the Pain](https://www.msaied.com/public/articles/postgresql-jsonb-in-laravel-indexing-querying-and-casting-without-the-pain-1)  

   On this page
-------------

1. [Why the Basics Are Not Enough](#why-the-basics-are-not-enough)
2. [Contextual Binding](#contextual-binding)
3. [Passing Primitive Values](#passing-primitive-values)
4. [Tagging Services](#tagging-services)
5. [Method Injection](#method-injection)
6. [Invokable Classes](#invokable-classes)
7. [Practical Patterns](#practical-patterns)
8. [Takeaways](#takeaways)

 ###  Have a technical challenge?

 Tell me what you’re building. I reply within two working days.

[Start a conversation](https://www.msaied.com/public#contact) 

   Related articles
-----------------

 [ ![](https://cdn.msaied.com/740/cce86edc21eddcbdd2f2454fadaf9c70.png)  · 3 min read### The Pipeline Pattern in Laravel: Custom Pipelines Beyond Middleware

5 Oct 2026 ](https://www.msaied.com/public/articles/the-pipeline-pattern-in-laravel-custom-pipelines-beyond-middleware-1) [ ![](https://cdn.msaied.com/739/2d6897fdcdcf090613f96f72a64b8a78.png)  · 4 min read### MySQL Full-Text Search in Laravel: Indexes, Relevance Scoring, and Boolean Mode

4 Oct 2026 ](https://www.msaied.com/public/articles/mysql-full-text-search-in-laravel-indexes-relevance-scoring-and-boolean-mode) [ ![](https://cdn.msaied.com/738/073696a3fefe18bec825beec5ac658f5.png)  · 4 min read### Laravel Queue Rate-Limited Middleware: Throttling Jobs Without Losing Work

4 Oct 2026 ](https://www.msaied.com/public/articles/laravel-queue-rate-limited-middleware-throttling-jobs-without-losing-work) 

  Have a technical challenge?
----------------------------

Tell me what you’re building. I reply within two working days.

 [Discuss your project ↗](https://www.msaied.com/public#contact) 

  © 2026 Mohamed Said · Built with Laravel, meant to last.Senior Backend Engineer specializing in Laravel, scalable SaaS platforms, APIs, and cloud infrastructure. I build secure, high-performance web applications that help businesses grow.

 - [Home](https://www.msaied.com/public)
- [Articles](https://www.msaied.com/public/articles)
- [Certificates](https://www.msaied.com/public/certificates)
- [GitHub](https://github.com/EG-Mohamed)
- [LinkedIn](https://www.linkedin.com/in/msaiedm/)
- [WhatsApp](https://wa.me/201094619204)
- [Email Address](mailto:hello@msaied.com)
- [My CV](https://drive.google.com/file/u/0/d/1MF20IPRJyzfy32mhEutjL5EpSls0w2Q8/view)
- [Sitemap](https://www.msaied.com/public/sitemap.xml)
