Vivek Mistry 👋

I’m a Certified Senior Laravel Developer with 6+ years of experience , specializing in building robust APIs and admin panels, frontend templates converting them into fully functional web applications.

Book A Call
  • 19 Nov, 2025
  • 722 Views
  • A hidden collection feature that helps you refactor messy code into elegant pipelines.

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

Share: