Laravel Pipeline Pattern Beyond Middleware | 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)    The Pipeline Pattern in Laravel: Building Custom Pipelines Beyond Middleware        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. [  Typing Your Payload with a DTO ](#typing-your-payload-with-a-dto)
4. [  Writing a Typed Stage ](#writing-a-typed-stage)
5. [  Conditional Pipes and Runtime Composition ](#conditional-pipes-and-runtime-composition)
6. [  Handling Failures Cleanly ](#handling-failures-cleanly)
7. [  Testing a Stage in Isolation ](#testing-a-stage-in-isolation)
8. [  Takeaways ](#takeaways)

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

  #laravel   #pipeline   #clean-architecture   #design-patterns  

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

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

       Table of contents

1. [  01   The Pipeline Pattern in Laravel: Beyond Middleware  ](#the-pipeline-pattern-in-laravel-beyond-middleware)
2. [  02   What the Pipeline Class Actually Does  ](#what-the-pipeline-class-actually-does)
3. [  03   Typing Your Payload with a DTO  ](#typing-your-payload-with-a-dto)
4. [  04   Writing a Typed Stage  ](#writing-a-typed-stage)
5. [  05   Conditional Pipes and Runtime Composition  ](#conditional-pipes-and-runtime-composition)
6. [  06   Handling Failures Cleanly  ](#handling-failures-cleanly)
7. [  07   Testing a Stage in Isolation  ](#testing-a-stage-in-isolation)
8. [  08   Takeaways  ](#takeaways)

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

Most Laravel developers know `Pipeline` as the engine behind HTTP middleware. Fewer realise it's a first-class citizen available anywhere in your application — and that it's one of the cleanest ways to model sequential, composable domain workflows.

This article shows how to build typed, testable pipelines for real business logic: order processing, document transformation, multi-step validation, and more.

---

What the Pipeline Class Actually Does
-------------------------------------

`Illuminate\Pipeline\Pipeline` passes a *payload* through an ordered list of *pipes*. Each pipe receives the payload and a `$next` closure. It can mutate the payload, short-circuit the chain, or simply delegate.

```php
use Illuminate\Pipeline\Pipeline;

$result = app(Pipeline::class)
    ->send($payload)
    ->through([
        StageOne::class,
        StageTwo::class,
        StageThree::class,
    ])
    ->thenReturn();

```

The default method called on each pipe is `handle`. You can override this:

```php
->via('process')

```

---

Typing Your Payload with a DTO
------------------------------

Untyped arrays as payloads are a maintenance trap. Use a readonly DTO:

```php
final readonly class OrderContext
{
    public function __construct(
        public Order $order,
        public ?Discount $discount = null,
        public bool $inventoryReserved = false,
        public bool $notificationSent = false,
    ) {}

    public function withDiscount(Discount $discount): self
    {
        return new self(
            order: $this->order,
            discount: $discount,
            inventoryReserved: $this->inventoryReserved,
            notificationSent: $this->notificationSent,
        );
    }
}

```

Each stage returns a new `OrderContext` rather than mutating state — immutability makes stages trivially testable in isolation.

---

Writing a Typed Stage
---------------------

```php
final class ApplyDiscountStage
{
    public function __construct(
        private readonly DiscountRepository $discounts,
    ) {}

    public function handle(OrderContext $context, Closure $next): OrderContext
    {
        $discount = $this->discounts->findForOrder($context->order);

        $context = $discount
            ? $context->withDiscount($discount)
            : $context;

        return $next($context);
    }
}

```

The container resolves constructor dependencies automatically, so `ApplyDiscountStage` is fully injectable without any extra wiring.

---

Conditional Pipes and Runtime Composition
-----------------------------------------

Pipelines shine when stage lists are dynamic:

```php
$pipes = [
    ValidateInventoryStage::class,
    ApplyDiscountStage::class,
];

if ($context->order->requiresExportCompliance()) {
    $pipes[] = ExportComplianceCheckStage::class;
}

$pipes[] = ReserveInventoryStage::class;
$pipes[] = SendConfirmationStage::class;

$result = app(Pipeline::class)
    ->send($context)
    ->through($pipes)
    ->thenReturn();

```

This is far cleaner than a chain of `if` blocks or a bloated service method.

---

Handling Failures Cleanly
-------------------------

Short-circuit by throwing a domain exception inside a stage:

```php
final class ValidateInventoryStage
{
    public function handle(OrderContext $context, Closure $next): OrderContext
    {
        if (! $this->inventory->isAvailable($context->order)) {
            throw new InsufficientInventoryException($context->order->id);
        }

        return $next($context);
    }
}

```

Wrap the pipeline call in a try/catch at the application layer. The pipeline itself stays free of error-handling noise.

---

Testing a Stage in Isolation
----------------------------

Because each stage is a plain class with a single `handle` method, Pest tests are minimal:

```php
it('applies a discount when one exists', function () {
    $order = Order::factory()->make();
    $discount = new Discount(percentage: 10);

    $repo = Mockery::mock(DiscountRepository::class);
    $repo->shouldReceive('findForOrder')->once()->andReturn($discount);

    $stage = new ApplyDiscountStage($repo);
    $context = new OrderContext(order: $order);

    $result = $stage->handle($context, fn ($ctx) => $ctx);

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

```

No HTTP, no database, no Kernel bootstrapping.

---

Takeaways
---------

- `Illuminate\Pipeline\Pipeline` is not HTTP-specific — use it anywhere sequential, composable logic is needed.
- Readonly DTOs as payloads give you immutability and IDE autocompletion throughout the chain.
- Stages are container-resolved classes: inject repositories, services, and config freely.
- Dynamic pipe arrays let you compose workflows at runtime based on domain rules.
- Each stage is independently unit-testable with zero framework overhead.

 Found this useful?

          [  ](https://twitter.com/intent/tweet?url=https%3A%2F%2Fmsaied.com%2Farticles%2Fthe-pipeline-pattern-in-laravel-building-custom-pipelines-beyond-middleware-2&text=The+Pipeline+Pattern+in+Laravel%3A+Building+Custom+Pipelines+Beyond+Middleware) [  ](https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fmsaied.com%2Farticles%2Fthe-pipeline-pattern-in-laravel-building-custom-pipelines-beyond-middleware-2) 

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

  3 questions  

     Q01  Can I reuse the same Pipeline instance across multiple requests in Octane?        No. Resolve a fresh Pipeline via `app(Pipeline::class)` or `new Pipeline(app())` per invocation. Storing a Pipeline instance as a singleton risks payload leakage between requests under Octane's persistent worker model. 

      Q02  How is this different from using a chain of Action classes?        Action chains require explicit orchestration code that calls each action in sequence. A Pipeline centralises that orchestration, supports dynamic stage lists, and provides a consistent short-circuit mechanism via exceptions or by not calling `$next`. 

      Q03  Can pipes be closures instead of classes?        Yes. The Pipeline accepts any callable, including closures. Classes are preferred for named, reusable, injectable stages; closures are fine for one-off transformations in tests or quick prototypes. 

  Continue reading

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

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

 [ ![Eloquent N+1 Elimination: Eager Loading Strategies and Query Deduplication at Scale](https://cdn.msaied.com/636/87a71d1826f8c6cce958da8377a0bdb9.png) laravel eloquent performance 

### Eloquent N+1 Elimination: Eager Loading Strategies and Query Deduplication at Scale

N+1 queries silently destroy Laravel app performance. This guide covers eager loading strategies, query dedupl...

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

 6 Sep 2026     4 min read  

  Read    

 ](https://msaied.com/articles/eloquent-n1-elimination-eager-loading-strategies-and-query-deduplication-at-scale) [ ![Laravel Job Middleware: Rate Limiting, Throttling, and Skipping Jobs Without Hacks](https://cdn.msaied.com/635/e10d72c500d7a25f077552f3098478e8.png) laravel queues job-middleware 

### Laravel Job Middleware: Rate Limiting, Throttling, and Skipping Jobs Without Hacks

Job middleware in Laravel lets you wrap queue job execution with reusable logic. Learn how to build rate-limit...

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

 6 Sep 2026     4 min read  

  Read    

 ](https://msaied.com/articles/laravel-job-middleware-rate-limiting-throttling-and-skipping-jobs-without-hacks) [ ![Filament v3 Infolist Entries: Building Rich Read-Only Detail Pages Without Blade Sprawl](https://cdn.msaied.com/634/13a8abbaba187864d69a5790a448ed46.png) filament laravel infolist 

### Filament v3 Infolist Entries: Building Rich Read-Only Detail Pages Without Blade Sprawl

Filament's Infolist API lets you compose structured, read-only detail views entirely in PHP. Learn how to buil...

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

 5 Sep 2026     3 min read  

  Read    

 ](https://msaied.com/articles/filament-v3-infolist-entries-building-rich-read-only-detail-pages-without-blade-sprawl) 

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