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 than the engine behind HTTP middleware. Learn how to compose reusable, testable processing chains for domain logic, data transformation, and multi-step workflows.

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

ShareCopy linkCopied

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

  On this page +1. [The Pipeline Pattern in Laravel: Beyond Middleware](#the-pipeline-pattern-in-laravel-beyond-middleware)
2. [What the Pipeline Class Actually Does](#what-the-pipeline-class-actually-does)
3. [Defining Pipe Classes](#defining-pipe-classes)
4. [Using a Custom Method Name](#using-a-custom-method-name)
5. [Short-Circuiting with Exceptions vs. Early Returns](#short-circuiting-with-exceptions-vs-early-returns)
6. [Resolving Pipes from the Container](#resolving-pipes-from-the-container)
7. [Testing Individual Pipes in Isolation](#testing-individual-pipes-in-isolation)
8. [When to Reach for a Pipeline](#when-to-reach-for-a-pipeline)
9. [Takeaways](#takeaways)

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

Most Laravel developers know `Pipeline` as the invisible machinery that runs HTTP middleware. Few reach for it when solving domain problems — and that's a missed opportunity. The `Illuminate\Pipeline\Pipeline` class is a first-class, general-purpose tool for building ordered, composable processing chains over any payload.

### What the Pipeline Class Actually Does

At its core, `Pipeline` wraps a passable value through an ordered list of stages (pipes), each of which can transform the value or short-circuit the chain. The contract is simple:

```php
use Illuminate\Pipeline\Pipeline;

$result = app(Pipeline::class)
    ->send($order)
    ->through([
        ValidateOrderInventory::class,
        ApplyLoyaltyDiscount::class,
        CalculateTax::class,
        ReserveStock::class,
    ])
    ->thenReturn();

```

Each pipe receives `($passable, $next)` — identical to middleware — but the passable is your domain object, not an HTTP request.

### Defining Pipe Classes

Implement the implicit pipe contract with a `handle` method:

```php
final class ApplyLoyaltyDiscount
{
    public function handle(Order $order, Closure $next): Order
    {
        if ($order->customer->hasLoyaltyTier()) {
            $order->applyDiscount(
                $order->customer->loyaltyDiscountRate()
            );
        }

        return $next($order);
    }
}

```

The pipe returns `$next($order)` to continue or returns early to short-circuit. No base class required — just a callable shape.

### Using a Custom Method Name

If you want a more expressive interface, define your own method and tell the pipeline:

```php
interface OrderPipe
{
    public function process(Order $order, Closure $next): Order;
}

$result = app(Pipeline::class)
    ->send($order)
    ->through($pipes)
    ->via('process')
    ->thenReturn();

```

This lets you enforce the interface in your pipe classes and get IDE autocompletion on the passable type.

### Short-Circuiting with Exceptions vs. Early Returns

Two clean patterns exist for halting a pipeline:

**Exception-based** — throw a domain exception inside a pipe; catch it at the call site:

```php
public function handle(Order $order, Closure $next): Order
{
    if ($order->total()->isZero()) {
        throw new InvalidOrderException('Order total cannot be zero.');
    }
    return $next($order);
}

```

**Result-object-based** — wrap the passable in a result DTO so pipes can inspect and propagate failure without exceptions:

```php
public function handle(OrderResult $result, Closure $next): OrderResult
{
    if ($result->failed()) {
        return $result; // skip remaining pipes
    }
    // ... mutate and continue
    return $next($result);
}

```

The result-object approach is friendlier to testing and avoids exception-as-control-flow.

### Resolving Pipes from the Container

String class names are resolved via the service container, so constructor injection works automatically:

```php
final class CalculateTax
{
    public function __construct(
        private readonly TaxRateRepository $rates
    ) {}

    public function handle(Order $order, Closure $next): Order
    {
        $order->setTax($this->rates->rateFor($order->shippingRegion()));
        return $next($order);
    }
}

```

No service locator boilerplate — the container handles it.

### Testing Individual Pipes in Isolation

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

```php
it('applies loyalty discount when customer has a tier', function () {
    $customer = Customer::factory()->withLoyaltyTier('gold')->make();
    $order = Order::factory()->for($customer)->make(['subtotal' => 100_00]);

    $pipe = new ApplyLoyaltyDiscount();
    $result = $pipe->handle($order, fn ($o) => $o);

    expect($result->discount())->toBe(10_00);
});

```

The `$next` closure is just an identity function in tests. No HTTP context, no mocking the pipeline itself.

### When to Reach for a Pipeline

- Multi-step import/export processing (CSV → validate → transform → persist)
- Order fulfilment workflows with optional stages
- Notification enrichment chains (resolve recipient → render template → choose channel)
- API response decoration across multiple transformers

### Takeaways

- `Pipeline` is a general-purpose tool — not HTTP-only.
- Pipes are plain classes resolved by the container; constructor injection is free.
- Use `->via('method')` to enforce a typed interface across all pipes.
- Result objects are cleaner than exceptions for expected failure paths.
- Each pipe is independently unit-testable with a simple identity `$next`.
- Pipelines make multi-step domain logic explicit, ordered, and easy to extend.

- [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 mix closure pipes and class-based pipes in the same pipeline?Yes. Laravel's Pipeline accepts any combination of class name strings, object instances, and closures in the `through()` array. Closures receive the same `($passable, $next)` signature as class-based pipes.

   How do I conditionally add a pipe based on runtime state?Build the pipes array before passing it to `through()`. Use a standard `if` statement or `array\_filter` to include or exclude specific pipe classes based on your domain conditions, then pass the final array to the pipeline.

   Is there a performance cost to using Pipeline for domain logic instead of plain method calls?The overhead is negligible for typical domain workflows — it amounts to a few closure wraps and container resolutions. Only in tight loops processing thousands of items per request would you consider inlining the logic, and even then profiling should guide that decision.

   ![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) [Next articleFilament v4 Schema-Based Forms: Unified Schema API in Practice](https://www.msaied.com/public/articles/filament-v4-schema-based-forms-unified-schema-api-in-practice)  

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

1. [The Pipeline Pattern in Laravel: Beyond Middleware](#the-pipeline-pattern-in-laravel-beyond-middleware)
2. [What the Pipeline Class Actually Does](#what-the-pipeline-class-actually-does)
3. [Defining Pipe Classes](#defining-pipe-classes)
4. [Using a Custom Method Name](#using-a-custom-method-name)
5. [Short-Circuiting with Exceptions vs. Early Returns](#short-circuiting-with-exceptions-vs-early-returns)
6. [Resolving Pipes from the Container](#resolving-pipes-from-the-container)
7. [Testing Individual Pipes in Isolation](#testing-individual-pipes-in-isolation)
8. [When to Reach for a Pipeline](#when-to-reach-for-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)
