Cleanly Process Business Logic in Laravel Using Pipeline
Laravel’s Pipeline allows developers to pass data through multiple logical steps in a clean and readable way. This article explains how Pipeline works with a real-world example that simplifies complex business flows.
Real Project Example: User Registration Flow
Imagine a registration process with these steps:
- Check if user is active
- Verify email
- Apply default settings
Instead of writing everything in one place, Pipeline keeps it readable.
use Illuminate\Support\Facades\Pipeline;
$user = Pipeline::send($user)
->through([
function ($user, $next) {
if (! $user->is_active) {
abort(403, 'Inactive user');
}
return $next($user);
},
function ($user, $next) {
$user->email_verified_at ??= now();
return $next($user);
},
function ($user, $next) {
$user->assignRole('user');
return $next($user);
},
])
->then(fn ($user) => $user);
Each step does one thing only.
Why Pipeline Is Better Than Conditions
Without Pipeline, you’d end up with:
- Nested
ifstatements - Hard-to-read logic
- Poor separation of concerns
With Pipeline:
- Each step is isolated
- Logic is reusable
- Flow is easy to understand
- Testing becomes simpler
When Pipeline Fits Perfectly
Use Pipeline when:
- Logic must run in a strict order
- Each step has a clear responsibility
- You want reusable business rules
- Controllers are getting too big
Avoid it when:
- Logic is very small
- A single method is enough