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)    Laravel Pipeline Pattern: Building Custom Pipelines Beyond Middleware        On this page       1. [  The Pipeline Pattern: Custom Pipelines Beyond Middleware ](#the-pipeline-pattern-custom-pipelines-beyond-middleware)
2. [  The Core API ](#the-core-api)
3. [  Typing Your Pipes ](#typing-your-pipes)
4. [  Injecting Dependencies Into Pipes ](#injecting-dependencies-into-pipes)
5. [  Conditional and Dynamic Pipe Lists ](#conditional-and-dynamic-pipe-lists)
6. [  Testing Pipelines With Pest ](#testing-pipelines-with-pest)
7. [  When Not to Use a Pipeline ](#when-not-to-use-a-pipeline)
8. [  Takeaways ](#takeaways)

  ![Laravel Pipeline Pattern: Building Custom Pipelines Beyond Middleware](https://cdn.msaied.com/524/bffe5038d4150b93f86c783df9f73d28.png)

  #laravel   #design-patterns   #architecture   #php  

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

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

       Table of contents

1. [  01   The Pipeline Pattern: Custom Pipelines Beyond Middleware  ](#the-pipeline-pattern-custom-pipelines-beyond-middleware)
2. [  02   The Core API  ](#the-core-api)
3. [  03   Typing Your Pipes  ](#typing-your-pipes)
4. [  04   Injecting Dependencies Into Pipes  ](#injecting-dependencies-into-pipes)
5. [  05   Conditional and Dynamic Pipe Lists  ](#conditional-and-dynamic-pipe-lists)
6. [  06   Testing Pipelines With Pest  ](#testing-pipelines-with-pest)
7. [  07   When Not to Use a Pipeline  ](#when-not-to-use-a-pipeline)
8. [  08   Takeaways  ](#takeaways)

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

Most Laravel developers know `Pipeline` only as the engine behind HTTP middleware. But the same `Illuminate\Pipeline\Pipeline` class is a first-class citizen you can use anywhere in your domain — order processing, import validation, data transformation, multi-step onboarding flows. If you have a value that must pass through an ordered sequence of discrete, swappable steps, a pipeline is the right tool.

### The Core API

The facade is straightforward:

```php
use Illuminate\Support\Facades\Pipeline;

$result = Pipeline::send($payload)
    ->through([
        NormalizeEmail::class,
        CheckDuplicateAccount::class,
        EnrichFromCRM::class,
        PersistRegistration::class,
    ])
    ->thenReturn();

```

`thenReturn()` returns the final `$payload`. Use `then(fn ($p) => ...)` when you need a custom terminal callback.

### Typing Your Pipes

Avoid the stringly-typed `$next` dance by defining a contract:

```php
namespace App\Pipelines\Registration;

interface RegistrationPipe
{
    public function handle(RegistrationData $data, \Closure $next): RegistrationData;
}

```

Each pipe implements the interface and returns the (possibly mutated) DTO:

```php
final class NormalizeEmail implements RegistrationPipe
{
    public function handle(RegistrationData $data, \Closure $next): RegistrationData
    {
        $data = $data->withEmail(mb_strtolower(trim($data->email)));

        return $next($data);
    }
}

```

Because each pipe receives and returns the same typed DTO, your IDE and static analysis tools (PHPStan, Psalm) can verify the entire chain at once.

### Injecting Dependencies Into Pipes

The `Pipeline` class resolves each pipe through the service container, so constructor injection works out of the box:

```php
final class CheckDuplicateAccount implements RegistrationPipe
{
    public function __construct(
        private readonly UserRepository $users,
    ) {}

    public function handle(RegistrationData $data, \Closure $next): RegistrationData
    {
        if ($this->users->existsByEmail($data->email)) {
            throw new DuplicateAccountException($data->email);
        }

        return $next($data);
    }
}

```

No service locator, no static calls — pure dependency injection.

### Conditional and Dynamic Pipe Lists

Build the pipe list at runtime based on context:

```php
$pipes = [
    NormalizeEmail::class,
    CheckDuplicateAccount::class,
];

if ($data->requiresCRMEnrichment()) {
    $pipes[] = EnrichFromCRM::class;
}

$pipes[] = PersistRegistration::class;

$result = Pipeline::send($data)->through($pipes)->thenReturn();

```

This is far cleaner than a chain of `if` statements scattered across a service class.

### Testing Pipelines With Pest

Because each pipe is a small, focused class, unit testing is trivial:

```php
it('lowercases and trims the email', function () {
    $pipe = new NormalizeEmail();
    $data = RegistrationData::from(email: '  FOO@EXAMPLE.COM  ');

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

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

```

For integration tests, swap a pipe with a fake:

```php
it('skips CRM enrichment in tests', function () {
    $result = Pipeline::send(RegistrationData::from(email: 'a@b.com'))
        ->through([
            NormalizeEmail::class,
            FakeEnrichFromCRM::class, // test double
            PersistRegistration::class,
        ])
        ->thenReturn();

    expect($result->id)->not->toBeNull();
});

```

### When Not to Use a Pipeline

Pipelines shine when steps are **ordered, swappable, and share the same payload type**. Avoid them for branching workflows (use a state machine), for fire-and-forget side effects (use events), or when steps need to communicate laterally rather than through the shared payload.

### Takeaways

- `Pipeline::send()->through()->thenReturn()` works anywhere, not just HTTP.
- Type your pipes with a shared interface and a DTO for IDE and static analysis support.
- The container resolves each pipe, so constructor injection is free.
- Build pipe lists dynamically for conditional processing logic.
- Each pipe is independently unit-testable; swap in test doubles for integration tests.
- Avoid pipelines for branching or lateral-communication workflows.

 Found this useful?

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

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

  3 questions  

     Q01  Can I pass object instances instead of class strings to `through()`?        Yes. `through()` accepts an array of class-name strings, already-resolved object instances, or a mix of both. When a string is given, the container resolves it (with DI); when an object is given, it is used directly. 

      Q02  How do I halt the pipeline early without throwing an exception?        The cleanest approach is to throw a domain exception and catch it at the call site. Alternatively, you can return the payload without calling `$next($data)` inside a pipe, which short-circuits the remaining steps and returns the current payload as the final result. 

      Q03  Is there a performance cost to using Pipeline over a plain service class?        The overhead is negligible — a small loop and container resolutions. For hot paths (thousands of calls per request), benchmark first, but for typical domain workflows the readability and testability gains far outweigh any micro-cost. 

  Continue reading

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

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

 [ ![PostgreSQL JSONB in Laravel: Indexing, Querying, and Casting Without the Chaos](https://cdn.msaied.com/526/bc43aae3afe723f9a29f47820735edf5.png) laravel postgresql jsonb 

### PostgreSQL JSONB in Laravel: Indexing, Querying, and Casting Without the Chaos

JSONB columns unlock flexible schemas, but without the right indexes and Eloquent integration they become a pe...

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

 9 Aug 2026     3 min read  

  Read    

 ](https://msaied.com/articles/postgresql-jsonb-in-laravel-indexing-querying-and-casting-without-the-chaos-2) [ ![Filament v4 Schema-Based Forms: Practical Patterns for the Unified Schema API](https://cdn.msaied.com/525/44fb6fe80b4b2439c1b1d9124976c67d.png) filament laravel filament-v4 

### Filament v4 Schema-Based Forms: Practical Patterns for the Unified Schema API

Filament v4 replaces scattered form/infolist definitions with a single Schema API. This post walks through rea...

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

 8 Aug 2026     3 min read  

  Read    

 ](https://msaied.com/articles/filament-v4-schema-based-forms-practical-patterns-for-the-unified-schema-api) [ ![Eloquent Query Optimization: Slaying N+1 Problems at Scale](https://cdn.msaied.com/523/a12bd8c82544aafcd6de50ff8c076141.png) laravel eloquent performance 

### Eloquent Query Optimization: Slaying N+1 Problems at Scale

N+1 queries silently kill Laravel app performance. This guide digs into eager loading strategies, query dedupl...

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

 8 Aug 2026     4 min read  

  Read    

 ](https://msaied.com/articles/eloquent-query-optimization-slaying-n1-problems-at-scale) 

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