Laravel Pipeline Pattern Beyond Middleware | 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. The Pipeline Pattern in Laravel: Building Custom Pipelines Beyond Middleware

 The Pipeline Pattern in Laravel: Building Custom Pipelines Beyond Middleware
=============================================================================

 Laravel's Pipeline class is far more powerful than middleware alone. Learn how to compose reusable, testable processing stages for domain workflows using the same primitive the framework uses internally.

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

ShareCopy linkCopied

 ![The Pipeline Pattern in Laravel: Building Custom Pipelines Beyond Middleware](https://cdn.msaied.com/359/fd848015c1e33ba7df4a1e9598454b5e.png) 

  On this page +1. [The Pipeline Pattern in Laravel: Beyond HTTP Middleware](#the-pipeline-pattern-in-laravel-beyond-http-middleware)
2. [Why Pipelines Over Plain Method Chains?](#why-pipelines-over-plain-method-chains)
3. [The Core API](#the-core-api)
4. [Writing a Stage](#writing-a-stage)
5. [Dynamic Stage Selection](#dynamic-stage-selection)
6. [A Typed Pipeline Wrapper](#a-typed-pipeline-wrapper)
7. [Testing Stages in Isolation](#testing-stages-in-isolation)
8. [When Not to Use a Pipeline](#when-not-to-use-a-pipeline)
9. [Takeaways](#takeaways)

 The Pipeline Pattern in Laravel: Beyond HTTP Middleware
-------------------------------------------------------

Most Laravel developers know `Pipeline` only as the engine behind HTTP middleware. But `Illuminate\Pipeline\Pipeline` is a first-class, general-purpose primitive you can reach for whenever you need to pass a payload through an ordered sequence of transformations — order processing, CSV imports, AI prompt enrichment, multi-step validation, and more.

### Why Pipelines Over Plain Method Chains?

A plain method chain couples every step to the caller. Pipelines decouple the *what* (the payload) from the *how* (the stages), letting you:

- Swap, reorder, or skip stages at runtime
- Test each stage in complete isolation
- Resolve stages from the service container (constructor injection works automatically)

### The Core API

```php
use Illuminate\Pipeline\Pipeline;

$result = app(Pipeline::class)
    ->send($payload)
    ->through([
        NormaliseInput::class,
        ValidateBusinessRules::class,
        PersistOrder::class,
        DispatchConfirmationEmail::class,
    ])
    ->thenReturn();

```

`thenReturn()` returns the (possibly mutated) payload after all stages. Use `then(fn ($p) => ...)` when you need a final transformation step.

### Writing a Stage

A stage is any class with a `handle` method — or any callable. The signature mirrors middleware:

```php
final class NormaliseInput
{
    public function handle(OrderData $data, Closure $next): OrderData
    {
        $data = $data->withNormalisedEmail(
            mb_strtolower(trim($data->email))
        );

        return $next($data);
    }
}

```

Because stages are resolved via the container, you can inject repositories, config, or services freely:

```php
final class ValidateBusinessRules
{
    public function __construct(
        private readonly ProductRepository $products,
    ) {}

    public function handle(OrderData $data, Closure $next): OrderData
    {
        foreach ($data->lines as $line) {
            throw_unless(
                $this->products->isAvailable($line->sku, $line->qty),
                InsufficientStockException::class,
                "SKU {$line->sku} is out of stock."
            );
        }

        return $next($data);
    }
}

```

### Dynamic Stage Selection

Stages don't have to be a static array. Build them at runtime based on context:

```php
$stages = collect([
    NormaliseInput::class,
    ValidateBusinessRules::class,
])
->when($order->requiresExportCompliance(), fn ($c) =>
    $c->push(ExportComplianceCheck::class)
)
->push(PersistOrder::class)
->all();

app(Pipeline::class)->send($order)->through($stages)->thenReturn();

```

### A Typed Pipeline Wrapper

For domain code, a thin wrapper improves discoverability and enforces the payload type:

```php
final class OrderProcessingPipeline
{
    public function __construct(private readonly Pipeline $pipeline) {}

    /** @param class-string[] $extraStages */
    public function process(OrderData $data, array $extraStages = []): OrderData
    {
        return $this->pipeline
            ->send($data)
            ->through([
                NormaliseInput::class,
                ValidateBusinessRules::class,
                ...$extraStages,
                PersistOrder::class,
            ])
            ->thenReturn();
    }
}

```

Bind it as a singleton and inject it wherever needed. Callers never touch the raw `Pipeline` class.

### Testing Stages in Isolation

Because each stage is a plain class, unit testing is trivial:

```php
it('normalises the email to lowercase', function () {
    $stage = new NormaliseInput();
    $data  = OrderData::fake(['email' => '  USER@Example.COM  ']);

    $result = $stage->handle($data, fn ($d) => $d);

    expect($result->email)->toBe('user@example.com');
});

```

No HTTP context, no database, no framework bootstrap required.

### When Not to Use a Pipeline

Pipelines shine when stages are interchangeable and the payload flows linearly. Avoid them when:

- Stages need to communicate laterally (use a saga or process manager instead)
- The flow is highly conditional with many branches (a state machine is clearer)
- You only have one or two steps (a simple service method is less indirection)

### Takeaways

- `Illuminate\Pipeline\Pipeline` is a general-purpose tool, not just for HTTP middleware.
- Stages are container-resolved classes — constructor injection works out of the box.
- Wrap the raw pipeline in a typed domain class to enforce payload contracts.
- Each stage is independently unit-testable with a simple closure as the `$next` stub.
- Build stage lists dynamically with `collect()->when()` for context-sensitive flows.

- [laravel](https://www.msaied.com/public/articles?search=laravel)
- [design-patterns](https://www.msaied.com/public/articles?search=design-patterns)
- [pipeline](https://www.msaied.com/public/articles?search=pipeline)
- [clean-architecture](https://www.msaied.com/public/articles?search=clean-architecture)

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

  Can I use closures as pipeline stages instead of classes?Yes. The `through()` method accepts any iterable of callables, including closures. Classes are preferred in production code because they are container-resolved, named, and independently testable, but closures are handy for quick ad-hoc stages or in tests.

   How do I stop the pipeline early, for example on a validation failure?Simply throw an exception inside the stage and do not call `$next`. Wrap the `thenReturn()` call in a try/catch at the call site. This keeps each stage's responsibility clear and avoids boolean flags polluting the payload.

   Is there a performance cost to using the Pipeline class compared to direct method calls?The overhead is negligible for typical domain workflows — a handful of container resolutions and closure calls. Only consider alternatives if you are running thousands of pipeline executions per request in a tight loop, which would be unusual.

   ![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 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-3) [Next articleFilament v4 Schema-Based Forms, Infolists, and the Unified Schema API](https://www.msaied.com/public/articles/filament-v4-schema-based-forms-infolists-and-the-unified-schema-api-2)  

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

1. [The Pipeline Pattern in Laravel: Beyond HTTP Middleware](#the-pipeline-pattern-in-laravel-beyond-http-middleware)
2. [Why Pipelines Over Plain Method Chains?](#why-pipelines-over-plain-method-chains)
3. [The Core API](#the-core-api)
4. [Writing a Stage](#writing-a-stage)
5. [Dynamic Stage Selection](#dynamic-stage-selection)
6. [A Typed Pipeline Wrapper](#a-typed-pipeline-wrapper)
7. [Testing Stages in Isolation](#testing-stages-in-isolation)
8. [When Not to Use a Pipeline](#when-not-to-use-a-pipeline)
9. [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)
