August 4, 2025

Laravel Pipelines: A Clean Way to Handle Complex Workflows

Use pipelines to break down multi-step logic into simple, testable classes

Tutorial
Laravel Pipelines: A Clean Way to Handle Complex Workflows

Introduction

Laravel's Pipeline class allows you to break down complex workflows into clean, testable steps. Instead of writing long if-else chains or deeply nested methods, you can move logic into individual “pipes” and run them in sequence.

This makes your code easier to test, easier to change, and easier to read.


Basic Example

Let’s say you receive $input from a form and want to clean it up before saving it.

use Illuminate\Pipeline\Pipeline; $data = app(Pipeline::class) ->send($input) ->through([ TrimInput::class, SanitizeEmail::class, ValidateRequiredFields::class, ]) ->thenReturn();

Each class in the through() array handles one step. Here’s how they work:


TrimInput Pipe

class TrimInput { public function handle(array $payload, Closure $next): array { $payload = array_map(fn($value) => is_string($value) ? trim($value) : $value, $payload); return $next($payload); } }

SanitizeEmail Pipe

class SanitizeEmail { public function handle(array $payload, Closure $next): array { if (isset($payload['email'])) { $payload['email'] = filter_var($payload['email'], FILTER_SANITIZE_EMAIL); } return $next($payload); } }

ValidateRequiredFields Pipe

use Illuminate\Validation\ValidationException; use Illuminate\Support\Facades\Validator; class ValidateRequiredFields { public function handle(array $payload, Closure $next): array { $validator = Validator::make($payload, [ 'name' => ['required', 'string'], 'email' => ['required', 'email'], ]); if ($validator->fails()) { throw new ValidationException($validator); } return $next($payload); } }

Real-World Use Cases

1. Payment Processing Flow

Break the flow into small pipes:

app(Pipeline::class) ->send($order) ->through([ CheckInventory::class, ApplyDiscount::class, ProcessPayment::class, SendInvoice::class, ]) ->thenReturn();

Summary

Laravel Pipelines let you organize complex logic into small, focused classes.

  • Improves readability and reusability
  • Great for data preprocessing, workflows, form steps, and more
  • Each pipe class is testable and single-responsibility

Using pipelines in Laravel is more than just clean syntax, it's about writing smarter, maintainable code.

Did you find this article helpful? Share it!