Tutorials Courses Interview Prep (100 Q&A) AI Tools (50) Developer Tools (50) Tracks Pricing Plans Blog & Articles Contact Us
Laravel Advanced & Architecture 5-8 Years (Senior) Medium

Explain the Pipeline pattern in Laravel and how middleware executes using Onion Architecture.

Real-World Scenario / Incident Description

An interviewer asks you to implement a custom data sanitizer pipeline from scratch using `Illuminate\Pipeline\Pipeline`.

729 views • Updated 1 month ago

Onion Architecture in Laravel

In Laravel, HTTP requests pass through middleware like layers of an onion. Middleware executes in sequence going inward, reaches the core route handler, and returns outward in reverse order.

Using Pipeline for Custom Business Logic

$sanitizedOrder = app(Pipeline::class)
    ->send($rawPayload)
    ->through([
        StripHtmlTags::class,
        NormalizePhoneNumbers::class,
        ApplyTaxExemptions::class,
        ValidatePromoCodes::class,
    ])
    ->then(fn ($payload) => Order::create($payload));

Each pipe implements a handle($passable, Closure $next) method:

class NormalizePhoneNumbers
{
    public function handle($payload, Closure $next)
    {
        $payload['phone'] = preg_replace('/[^0-9+]/', '', $payload['phone']);
        return $next($payload);
    }
}
Related Concepts: #Pipeline Pattern #Middleware #Design Patterns #Architecture