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: Custom Pipelines Beyond Middleware

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

 Laravel's Pipeline class is far more than the engine behind HTTP middleware. Learn how to build typed, testable pipelines for domain workflows, data transformation, and multi-step validation without coupling logic to controllers.

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

ShareCopy linkCopied

 ![The Pipeline Pattern in Laravel: Custom Pipelines Beyond Middleware](https://cdn.msaied.com/419/65618d839987270b780e652bfdf22cfe.png) 

  On this page +1. [The Pipeline Pattern in Laravel: Custom Pipelines Beyond Middleware](#the-pipeline-pattern-in-laravel-custom-pipelines-beyond-middleware)
2. [What the Pipeline Actually Does](#what-the-pipeline-actually-does)
3. [Typed Passables: Use a DTO](#typed-passables-use-a-dto)
4. [Writing a Pipe Class](#writing-a-pipe-class)
5. [Short-Circuiting the Pipeline](#short-circuiting-the-pipeline)
6. [Assembling the Pipeline as a Service](#assembling-the-pipeline-as-a-service)
7. [Testing with Pest](#testing-with-pest)
8. [Takeaways](#takeaways)

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

Most Laravel developers know `Illuminate\Pipeline\Pipeline` only as the machinery that runs HTTP middleware. That's a shame — it's one of the cleanest abstractions in the framework, and it maps perfectly onto domain workflows: order processing, document ingestion, multi-step imports, and anything else that passes a single object through a sequence of transformations.

### What the Pipeline Actually Does

At its core, `Pipeline::send($passable)->through($pipes)->thenReturn()` builds a nested closure stack and calls it. Each pipe receives the passable and a `$next` callable. That's it. No magic, no hidden state.

```php
use Illuminate\Pipeline\Pipeline;

$result = app(Pipeline::class)
    ->send($passable)
    ->through([
        PipeA::class,
        PipeB::class,
    ])
    ->thenReturn();

```

The default method invoked on each class is `handle($passable, Closure $next)`. You can override this with `->via('process')` if your pipes already have a different contract.

### Typed Passables: Use a DTO

Passing a plain array through a pipeline is asking for bugs. Use a mutable DTO so every pipe has a typed contract.

```php
final class OrderImportContext
{
    public function __construct(
        public readonly array $rawRow,
        public ?Product $product = null,
        public ?Customer $customer = null,
        public array $errors = [],
    ) {}

    public function addError(string $message): void
    {
        $this->errors[] = $message;
    }

    public function hasErrors(): bool
    {
        return count($this->errors) > 0;
    }
}

```

Each pipe reads from and writes to this context. Nothing leaks outside the pipeline.

### Writing a Pipe Class

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

    public function handle(OrderImportContext $context, Closure $next): OrderImportContext
    {
        $sku = $context->rawRow['sku'] ?? null;

        if (! $sku) {
            $context->addError('Missing SKU');
            return $next($context); // continue; downstream pipes may still run
        }

        $context->product = $this->products->findBySku($sku);

        if (! $context->product) {
            $context->addError("Unknown SKU: {$sku}");
        }

        return $next($context);
    }
}

```

Because pipes are resolved via the service container, constructor injection works out of the box.

### Short-Circuiting the Pipeline

Sometimes you want to halt on the first error. Simply don't call `$next`:

```php
public function handle(OrderImportContext $context, Closure $next): OrderImportContext
{
    if ($context->hasErrors()) {
        return $context; // bail early, skip remaining pipes
    }

    // ... do work

    return $next($context);
}

```

This is the same mechanism Laravel's own `CheckForMaintenanceMode` middleware uses.

### Assembling the Pipeline as a Service

Don't scatter `app(Pipeline::class)` calls across your codebase. Wrap it:

```php
final class OrderImportPipeline
{
    private array $pipes = [
        ResolveProduct::class,
        ResolveCustomer::class,
        ValidateQuantity::class,
        PersistOrder::class,
    ];

    public function __construct(
        private readonly Pipeline $pipeline,
    ) {}

    public function run(array $rawRow): OrderImportContext
    {
        return $this->pipeline
            ->send(new OrderImportContext($rawRow))
            ->through($this->pipes)
            ->thenReturn();
    }
}

```

Bind it in a service provider and inject it wherever needed.

### Testing with Pest

Because each pipe is a plain class, you can test them in isolation:

```php
it('adds an error when SKU is missing', function () {
    $pipe = new ResolveProduct(
        products: Mockery::mock(ProductRepository::class),
    );

    $context = new OrderImportContext(rawRow: []);
    $result = $pipe->handle($context, fn ($ctx) => $ctx);

    expect($result->errors)->toContain('Missing SKU');
});

```

And the full pipeline as an integration test:

```php
it('persists a valid order row end-to-end', function () {
    $pipeline = app(OrderImportPipeline::class);
    $context = $pipeline->run(['sku' => 'WIDGET-1', 'qty' => 2, 'customer_id' => 1]);

    expect($context->hasErrors())->toBeFalse()
        ->and(Order::count())->toBe(1);
});

```

### Takeaways

- `Pipeline` is a first-class Laravel primitive — use it for any sequential, composable workflow.
- A typed DTO passable eliminates silent type errors and makes each pipe self-documenting.
- Pipes are container-resolved, so full DI is available without any extra wiring.
- Short-circuit by returning early without calling `$next`; continue by always calling it.
- Wrapping the pipeline in a dedicated service class keeps assembly logic in one place and makes the pipeline trivially swappable in tests.

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

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

  Can I pass a pipeline instance through the service container and swap pipes per context?Yes. Bind your pipeline wrapper in a service provider and use contextual binding or a factory method to inject different pipe sets for different contexts — for example, a stricter validation pipe set for API imports versus a lenient one for admin bulk uploads.

   Is there a performance cost to using Pipeline over a plain foreach loop?The overhead is negligible for typical domain workflows. Pipeline builds a closure stack once per invocation, which adds microseconds. For tight loops processing thousands of rows per second, a plain loop is faster, but for most business logic the readability and testability gains outweigh any micro-benchmark difference.

   How do I handle exceptions thrown inside a pipe?Exceptions bubble up normally through the closure stack. Wrap your `thenReturn()` call in a try/catch at the call site, or add a dedicated exception-catching pipe at the start of the pipeline that wraps `$next($context)` in a try/catch and records the error on the context object.

   ![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 articleUvora: A macOS Menu Bar App for Finding Laravel Projects Instantly](https://www.msaied.com/public/articles/uvora-a-macos-menu-bar-app-for-finding-laravel-projects-instantly) [Next articlePostgreSQL Full-Text Search in Laravel: Indexes, ts\_rank, and Weighted Queries](https://www.msaied.com/public/articles/postgresql-full-text-search-in-laravel-indexes-ts-rank-and-weighted-queries)  

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

1. [The Pipeline Pattern in Laravel: Custom Pipelines Beyond Middleware](#the-pipeline-pattern-in-laravel-custom-pipelines-beyond-middleware)
2. [What the Pipeline Actually Does](#what-the-pipeline-actually-does)
3. [Typed Passables: Use a DTO](#typed-passables-use-a-dto)
4. [Writing a Pipe Class](#writing-a-pipe-class)
5. [Short-Circuiting the Pipeline](#short-circuiting-the-pipeline)
6. [Assembling the Pipeline as a Service](#assembling-the-pipeline-as-a-service)
7. [Testing with Pest](#testing-with-pest)
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)
