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 powers middleware, but it's equally powerful for domain workflows. Learn how to build typed, testable pipelines for complex business logic without coupling to HTTP.

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

ShareCopy linkCopied

 ![The Pipeline Pattern in Laravel: Building Custom Pipelines Beyond Middleware](https://cdn.msaied.com/637/1b6b067bc3805768f8e1f546d2ba7545.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. [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: 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.

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

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

  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.

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

   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.

   ![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 articleEloquent N+1 Elimination: Eager Loading Strategies and Query Deduplication at Scale](https://www.msaied.com/public/articles/eloquent-n1-elimination-eager-loading-strategies-and-query-deduplication-at-scale) [Next articleFilament v4 Schema-Based Forms: Unified Schema API and Infolist Patterns](https://www.msaied.com/public/articles/filament-v4-schema-based-forms-unified-schema-api-and-infolist-patterns)  

   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)

 ###  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)
