Laravel Service Container: Contextual Binding Guide | 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)    Contextual Binding and Method Injection in Laravel's Service Container        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)

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

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

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

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

       Table of contents

1. [  01   Why the Basics Are Not Enough  ](#why-the-basics-are-not-enough)
2. [  02   Contextual Binding  ](#contextual-binding)
3. [  03   Passing Primitive Values  ](#passing-primitive-values)
4. [  04   Tagging Services  ](#tagging-services)
5. [  05   Method Injection  ](#method-injection)
6. [  06   Invokable Classes  ](#invokable-classes)
7. [  07   Practical Patterns  ](#practical-patterns)
8. [  08   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.

 Found this useful?

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

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

  3 questions  

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

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

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

  Continue reading

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

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

 [ ![Cursor Pagination and Lazy Collections at Scale in Laravel](https://cdn.msaied.com/536/3aab48ef4a4eaa26a3267637dc2ec8c7.png) laravel eloquent performance 

### Cursor Pagination and Lazy Collections at Scale in Laravel

Offset pagination breaks under large datasets. Learn how Laravel's cursor pagination and lazy collections let...

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

 11 Aug 2026     3 min read  

  Read    

 ](https://msaied.com/articles/cursor-pagination-and-lazy-collections-at-scale-in-laravel) [ ![Livewire v3.8.4 Released: Octane Memory Leak Fix and Fetch Redirect Handling](https://cdn.msaied.com/534/fdb2d91db2cb26fba0788d205b663031.png) livewire laravel octane 

### Livewire v3.8.4 Released: Octane Memory Leak Fix and Fetch Redirect Handling

Livewire v3.8.4 ships two important backports: a fix for a computed property listener memory leak under Larave...

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

 10 Aug 2026     3 min read  

  Read    

 ](https://msaied.com/articles/livewire-v384-released-octane-memory-leak-fix-and-fetch-redirect-handling) [ ![Laravel artisan dev: Run Server, Queue, Logs, and Vite in One Command](https://cdn.msaied.com/533/88ab98460b08aed42d6688eaa02a9620.png) Laravel Artisan Laravel 13 

### Laravel artisan dev: Run Server, Queue, Logs, and Vite in One Command

Laravel 13.16 introduced a first-party `php artisan dev` command that replaces the old Composer script, runnin...

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

 10 Aug 2026     3 min read  

  Read    

 ](https://msaied.com/articles/laravel-artisan-dev-run-server-queue-logs-and-vite-in-one-command) 

   [  ![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)
