pipe() in Laravel
pipe() lets you pass a value into a callback, get a transformed value, and continue the chain.
It’s basically:
“Take this value → run it through a function → return whatever the function returns.”
💡 Why it's useful?
- Helps clean up messy logic
- Let’s you apply small transformations inside a chain
- Keeps code easy to read & test
Without pipe()
$amount = (new Payment)->calculateTotal();
$amount = $amount * 1.18; // add GST
$amount = round($amount, 2); // round to 2 decimals
With pipe()
$amount = (new Payment)->calculateTotal()
->pipe(fn ($amt) => $amt * 1.18)
->pipe(fn ($amt) => round($amt, 2));
Example: Transforming an Order Amount
Without pipe()
$total = $order->subtotal();
if ($user->hasCoupon()) {
$total = $total - $user->coupon->discount;
}
$total = $total * 1.05; // 5% platform fee
$total = max($total, 50); // minimum charge
With pipe() (Cleaner)
$total = $order->subtotal()
->pipe(fn ($t) => $user->hasCoupon() ? $t - $user->coupon->discount : $t)
->pipe(fn ($t) => $t * 1.05) // platform fee
->pipe(fn ($t) => max($t, 50)); // minimum amount