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. Laravel Pipeline Pattern: Building Custom Pipelines Beyond Middleware

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

 The Pipeline pattern in Laravel is far more powerful than middleware alone. Learn how to compose reusable, testable processing stages for domain workflows using the built-in Pipeline facade.

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

ShareCopy linkCopied

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

  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)

 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.

- [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)
- [php](https://www.msaied.com/public/articles?search=php)

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

  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.

   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.

   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.

   ![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 Query Optimization: Slaying N+1 Problems at Scale](https://www.msaied.com/public/articles/eloquent-query-optimization-slaying-n1-problems-at-scale) [Next articleFilament v4 Schema-Based Forms: Practical Patterns for the Unified Schema API](https://www.msaied.com/public/articles/filament-v4-schema-based-forms-practical-patterns-for-the-unified-schema-api)  

   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)

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