Laravel Service Container: Contextual Binding &amp; Injection | 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 singleton registration. 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 7 Sep 2026 · Updated 7 Sep 2026 · 3 min read

ShareCopy linkCopied

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

  On this page +1. [Beyond app()-&gt;make(): The Container You're Not Using Fully](#beyond-codeapp-gtmakecode-the-container-youre-not-using-fully)
2. [Contextual Binding](#contextual-binding)
3. [Giving a Primitive Contextually](#giving-a-primitive-contextually)
4. [Tagged Services](#tagged-services)
5. [Method Injection](#method-injection)
6. [Method Injection in Artisan Commands](#method-injection-in-artisan-commands)
7. [Testing Contextual Bindings](#testing-contextual-bindings)
8. [Takeaways](#takeaways)

 Beyond `app()->make()`: The Container You're Not Using Fully
------------------------------------------------------------

Most Laravel developers know `bind`, `singleton`, and `make`. That covers 80% of day-to-day container use. The remaining 20% — contextual binding, tagged services, and method injection — is where the container earns its keep in complex domain code. This article walks through each with production-grade examples.

---

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(OrderProcessor::class)
    ->needs(PaymentGatewayInterface::class)
    ->give(StripeGateway::class);

$this->app
    ->when(SubscriptionRenewalJob::class)
    ->needs(PaymentGatewayInterface::class)
    ->give(BraintreeGateway::class);

```

Both `OrderProcessor` and `SubscriptionRenewalJob` type-hint `PaymentGatewayInterface`. The container resolves each to a different concrete without any conditional logic inside the classes themselves.

### Giving a Primitive Contextually

Contextual binding isn't limited to interfaces. You can inject config values or primitive scalars:

```php
$this->app
    ->when(S3Uploader::class)
    ->needs('$bucketName')
    ->give(fn () => config('filesystems.disks.s3.bucket'));

```

The `$bucketName` constructor parameter is resolved from config at build time — no `config()` call inside the class, no hidden coupling.

---

Tagged Services
---------------

Tagging lets you resolve a *collection* of implementations registered under a shared label. This is the clean alternative to a hand-rolled registry array.

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

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

```

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

// In the service provider
$this->app->bind(ExportManager::class, fn ($app) =>
    new ExportManager($app->tagged('exporters'))
);

```

`$app->tagged()` returns a lazy generator — implementations are not instantiated until iterated. Adding a new exporter is a one-line tag registration; `ExportManager` never changes.

---

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

The container can inject dependencies into *arbitrary methods*, not just constructors. This is useful for controller actions, console commands, and domain handlers where you want to keep the constructor lean.

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

```

Laravel's router already does this for controller methods. You can invoke the same mechanism manually:

```php
$result = app()->call(
    [SomeService::class, 'handle'],
    ['extraParam' => $value]  // merge with container-resolved args
);

```

This is powerful inside pipeline stages, command handlers, or test helpers where you want full DI without making the class a singleton.

### Method Injection in Artisan Commands

```php
class SyncInventoryCommand extends Command
{
    public function handle(InventorySync $sync, LoggerInterface $log): int
    {
        $log->info('Starting sync');
        $sync->run();
        return self::SUCCESS;
    }
}

```

Artisan resolves `handle()` through the container automatically. No constructor injection needed for command-specific dependencies.

---

Testing Contextual Bindings
---------------------------

Swap a contextual binding in a test without touching the service provider:

```php
it('uses the sandbox gateway in tests', function () {
    $this->app
        ->when(OrderProcessor::class)
        ->needs(PaymentGatewayInterface::class)
        ->give(SandboxGateway::class);

    $processor = app(OrderProcessor::class);

    expect($processor->gateway())->toBeInstanceOf(SandboxGateway::class);
});

```

The override is scoped to the test; no global state leaks.

---

Takeaways
---------

- **Contextual binding** eliminates conditional logic inside classes when multiple implementations of an interface are needed in different contexts.
- **Primitive injection** (`needs('$param')`) keeps config and environment values out of class bodies.
- **Tagged services** replace hand-rolled registries with a lazy, extensible collection resolved by the container.
- **Method injection via `app()->call()`** gives you full DI on any callable — useful in pipelines, handlers, and tests.
- All of these are testable in isolation: swap bindings per-test without touching service providers.

- [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 or strategy pattern?Use contextual binding when the decision of which implementation to use is purely about \*which class is being constructed\*, not runtime data. If the choice depends on user input or a database value, a factory or strategy resolved at runtime is more appropriate.

   Does `app()-&gt;tagged()` instantiate all services immediately?No. `app()-&gt;tagged()` returns a generator. Each implementation is resolved lazily as you iterate, so unused implementations in the collection are never instantiated.

   Can I use method injection outside of controllers and Artisan commands?Yes. `app()-&gt;call($callable, $parameters)` works on any callable — closures, static methods, or instance methods. The container merges your explicit parameters with anything it can resolve by type-hint.

   ![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 articleFind Unexpected Test Inputs with Fuzz for Pest](https://www.msaied.com/public/articles/find-unexpected-test-inputs-with-fuzz-for-pest) [Next articleFilament v4.13.0 Released: Deferred Schema Loading, Session Grouping &amp; More](https://www.msaied.com/public/articles/filament-v4130-released-deferred-schema-loading-session-grouping-more)  

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

1. [Beyond app()-&gt;make(): The Container You're Not Using Fully](#beyond-codeapp-gtmakecode-the-container-youre-not-using-fully)
2. [Contextual Binding](#contextual-binding)
3. [Giving a Primitive Contextually](#giving-a-primitive-contextually)
4. [Tagged Services](#tagged-services)
5. [Method Injection](#method-injection)
6. [Method Injection in Artisan Commands](#method-injection-in-artisan-commands)
7. [Testing Contextual Bindings](#testing-contextual-bindings)
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)
