Laravel Service Container: Contextual Binding &amp; Tagging | 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. Laravel Service Container: Contextual Binding, Tagging, and Method Injection

 Laravel Service Container: Contextual Binding, Tagging, and Method Injection
=============================================================================

 Go beyond basic singleton registration. Learn how contextual binding, container tags, and method injection let you write genuinely decoupled Laravel code without reaching for a service locator.

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

ShareCopy linkCopied

 ![Laravel Service Container: Contextual Binding, Tagging, and Method Injection](https://cdn.msaied.com/497/984bfdafd47db8cd56c71d9293c3dc25.png) 

  On this page +1. [Beyond app()-&gt;make(): The Container Features You're Probably Underusing](#beyond-codeapp-gtmakecode-the-container-features-youre-probably-underusing)
2. [Contextual Binding](#contextual-binding)
3. [Contextual Primitives](#contextual-primitives)
4. [Container Tagging](#container-tagging)
5. [Method Injection](#method-injection)
6. [Practical Takeaways](#practical-takeaways)

 Beyond `app()->make()`: The Container Features You're Probably Underusing
-------------------------------------------------------------------------

Most Laravel developers know `bind`, `singleton`, and `make`. What separates a well-architected application from a tangled one is often the *other* container features: contextual binding, tagging, and method injection. Let's go deep on each.

---

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

Contextual binding answers the question: *what should the container inject when two different classes both depend on the same interface, but need different implementations?*

```php
// AppServiceProvider::register()

$this->app
    ->when(ReportExporter::class)
    ->needs(StorageInterface::class)
    ->give(S3Storage::class);

$this->app
    ->when(LocalPreviewGenerator::class)
    ->needs(StorageInterface::class)
    ->give(LocalDiskStorage::class);

```

Both classes declare `StorageInterface` in their constructors. The container resolves the correct implementation based on *who is asking*, not just *what is needed*. No factory, no service locator, no `if` branch in a shared provider.

You can also pass a closure for runtime logic:

```php
$this->app
    ->when(TenantMailer::class)
    ->needs(TransportInterface::class)
    ->give(function ($app) {
        return $app->make(
            config('mail.tenant_transport') === 'ses'
                ? SesTransport::class
                : SmtpTransport::class
        );
    });

```

### Contextual Primitives

Since Laravel 10 you can also inject primitive values contextually using `giveConfig` or a plain closure:

```php
$this->app
    ->when(StripeGateway::class)
    ->needs('$apiKey')
    ->giveConfig('services.stripe.secret');

```

This removes the need for a dedicated config-reading constructor or a value object just to carry a string.

---

Container Tagging
-----------------

Tagging lets you group related bindings and resolve them all at once — perfect for plugin systems, report drivers, or notification channels.

```php
// Register
$this->app->bind(CsvExporter::class);
$this->app->bind(XlsxExporter::class);
$this->app->bind(PdfExporter::class);

$this->app->tag(
    [CsvExporter::class, XlsxExporter::class, PdfExporter::class],
    'exporters'
);

```

```php
// Resolve all tagged bindings
class ExportManager
{
    /** @param iterable $exporters */
    public function __construct(
        private readonly iterable $exporters
    ) {}
}

// In the provider
$this->app->bind(ExportManager::class, function ($app) {
    return new ExportManager($app->tagged('exporters'));
});

```

`$app->tagged()` returns a lazy `Generator`, so bindings are not instantiated until iterated. This matters when exporters have heavy constructors.

---

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

The container can inject dependencies into *arbitrary methods*, not just constructors. This is how route closures and controller methods work internally, and you can use the same mechanism in your own code.

```php
class ReportController
{
    public function generate(
        Request $request,
        ReportBuilder $builder,   // injected by container
        AuditLogger $logger       // injected by container
    ): JsonResponse {
        // ...
    }
}

```

You can call any callable through the container with `app()->call()`:

```php
$result = app()->call(
    [new InvoiceProcessor(), 'process'],
    ['invoiceId' => $id]   // extra primitives merged in
);

```

This is particularly useful in pipeline stages, console commands, or action classes where you want the container to satisfy type-hinted dependencies without making every class a full service.

```php
// Action resolved and called without manual wiring
$result = app()->call(GenerateInvoiceAction::class, [
    'order' => $order,
]);

```

---

Practical Takeaways
-------------------

- **Contextual binding** eliminates conditional logic in providers when the same interface needs different implementations per consumer.
- **`giveConfig`** keeps primitive injection declarative and avoids leaking config calls into constructors.
- **Tagging** is the cleanest way to implement open/closed plugin systems — add a new driver by registering and tagging it, nothing else changes.
- **`app()->call()`** gives you full DI on any callable, making action classes and pipeline stages first-class container citizens.
- Prefer contextual binding over abstract factories when the variation is *per-consumer*, not *per-runtime-value*.

- [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 variation is static and known at registration time — different consumers need different implementations. Use a factory when the correct implementation depends on runtime data such as a tenant ID or user preference.

   Does `app()-&gt;tagged()` instantiate all bindings immediately?No. `tagged()` returns a Generator, so each binding is resolved lazily as you iterate. This avoids unnecessary construction costs if you break out of the loop early or only need a subset of tagged services.

   Can method injection be used outside of controllers?Yes. Any callable — a closure, an array callable like `\[$object, 'method'\]`, or a class@method string — can be resolved through `app()-&gt;call()`. Extra primitive arguments can be passed as the second parameter and are merged with container-resolved dependencies.

   ![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 articleLaravel Eloquent Global vs Local Scopes: Pitfalls, Ordering, and Scope Composition](https://www.msaied.com/public/articles/laravel-eloquent-global-vs-local-scopes-pitfalls-ordering-and-scope-composition) [Next articleRead/Write Splitting, Connection Pooling, and Sticky Reads in Laravel](https://www.msaied.com/public/articles/readwrite-splitting-connection-pooling-and-sticky-reads-in-laravel-5)  

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

1. [Beyond app()-&gt;make(): The Container Features You're Probably Underusing](#beyond-codeapp-gtmakecode-the-container-features-youre-probably-underusing)
2. [Contextual Binding](#contextual-binding)
3. [Contextual Primitives](#contextual-primitives)
4. [Container Tagging](#container-tagging)
5. [Method Injection](#method-injection)
6. [Practical Takeaways](#practical-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)
