Laravel Service Container: Contextual Binding &amp; Tagging | Mohamed Said        [  ![Mohamed Said](https://cdn.msaied.com/01KT78WE565VEMM3PSNQAAB0MH.png)   Mohamed Said Laravel Backend Engineer  ](https://msaied.com) [ Home ](https://msaied.com) [ Projects ](https://msaied.com/projects) [ Articles  ](https://msaied.com/articles) [ Certificates ](https://msaied.com/certificates) [ Contact ](https://msaied.com#contact-section) 

       [  ](https://github.com/EG-Mohamed)       

 [ Home ](https://msaied.com) [ Projects ](https://msaied.com/projects) [ Articles ](https://msaied.com/articles) [ Certificates ](https://msaied.com/certificates) [ Contact ](https://msaied.com#contact-section) 

  [ home ](https://msaied.com)    [ articles ](https://msaied.com/articles)    Laravel Service Container: Contextual Binding, Tagging, and Method Injection        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)

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

  #laravel   #service-container   #dependency-injection   #architecture  

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

     1 Aug 2026      3 min read    ![Mohamed Said](https://cdn.msaied.com/01KT78WE565VEMM3PSNQAAB0MJ.jpg)  Mohamed Said  

       Table of contents

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

 Found this useful?

          [  ](https://twitter.com/intent/tweet?url=https%3A%2F%2Fmsaied.com%2Farticles%2Flaravel-service-container-contextual-binding-tagging-and-method-injection-3&text=Laravel+Service+Container%3A+Contextual+Binding%2C+Tagging%2C+and+Method+Injection) [  ](https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fmsaied.com%2Farticles%2Flaravel-service-container-contextual-binding-tagging-and-method-injection-3) 

 Frequently Asked Questions 
----------------------------

  3 questions  

     Q01  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. 

      Q02  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. 

      Q03  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. 

  Continue reading

 More Articles 
---------------

 [ View all    ](https://msaied.com/articles) 

 [ ![PhpStorm 2026.2 Released: Laravel Tool Window, PHP 8.5 Pipe Operator, and AI Agents](https://cdn.msaied.com/505/151a0bba66cc27064e090e69e55d7c92.png) PhpStorm JetBrains PHP 8.5 

### PhpStorm 2026.2 Released: Laravel Tool Window, PHP 8.5 Pipe Operator, and AI Agents

PhpStorm 2026.2 ships a dedicated Laravel tool window with Artisan, error logs, and Laravel Cloud tabs, plus P...

  ![Mohamed Said](https://cdn.msaied.com/01KT78WE565VEMM3PSNQAAB0MJ.jpg)  Mohamed Said 

 3 Aug 2026     3 min read  

  Read    

 ](https://msaied.com/articles/phpstorm-20262-released-laravel-tool-window-php-85-pipe-operator-and-ai-agents) [ ![Laravel Doctor: Diagnose Your Laravel App With One Artisan Command](https://cdn.msaied.com/504/d72224689abc7b396bce187535008272.png) Laravel Artisan Health Checks 

### Laravel Doctor: Diagnose Your Laravel App With One Artisan Command

Laravel Doctor is a first-party package announced at Laracon US 2026 that adds an `artisan doctor` command to...

  ![Mohamed Said](https://cdn.msaied.com/01KT78WE565VEMM3PSNQAAB0MJ.jpg)  Mohamed Said 

 3 Aug 2026     4 min read  

  Read    

 ](https://msaied.com/articles/laravel-doctor-diagnose-your-laravel-app-with-one-artisan-command) [ ![Livewire v4.3.5 Released: Fix for SFC Detection with PHP Attribute Array Arguments](https://cdn.msaied.com/503/9678ed8dbf5d7a6f4f19ca7694cf241b.png) Livewire Laravel PHP 

### Livewire v4.3.5 Released: Fix for SFC Detection with PHP Attribute Array Arguments

Livewire v4.3.5 ships a targeted bug fix for Single File Component (SFC) detection when PHP attributes contain...

  ![Mohamed Said](https://cdn.msaied.com/01KT78WE565VEMM3PSNQAAB0MJ.jpg)  Mohamed Said 

 3 Aug 2026     2 min read  

  Read    

 ](https://msaied.com/articles/livewire-v435-released-fix-for-sfc-detection-with-php-attribute-array-arguments) 

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

Explore

- [Home](https://msaied.com)
- [Projects](https://msaied.com/projects)
- [Articles](https://msaied.com/articles)
- [Certificates](https://msaied.com/certificates)
- [Contact](https://msaied.com#contact-section)

Connect

- [   hello@msaied.com ](mailto:hello@msaied.com)
- [   +20 109 461 9204 ](tel:+201094619204)

© 2026 Mohamed Said. All rights reserved.

 [  ](https://github.com/EG-Mohamed) [  ](https://www.linkedin.com/in/msaiedm/) [  ](https://wa.me/201094619204) [  ](mailto:hello@msaied.com) [  ](https://drive.google.com/file/u/0/d/1MF20IPRJyzfy32mhEutjL5EpSls0w2Q8/view)
