Pipeline is one of Laravel's less-known features. It's often used in the framework itself, for example routing, but not so many developers use it.
This is the Controller, where we create the Pipeline: class OrderController extends Controller { public function store(Request $request) { $order = Order::create([ 'customer_name' => $request->customerName, 'net_amount' => $request->netAmount, 'pay_amount' => $request->netAmount, ]); $pipes = [ ApplyDiscount::class, AddVat::class, AddShipping::class, ]; $order = app(Pipeline::class) ->send($order) ->through($pipes) ->then(function (Order $order) { $order->save(); return $order; }); return response($order, Response::HTTP_CREATED); }}
class AddShipping { public function handle(Order $order, Closure $next): Order { $order->pay_amount += 10; return $next($order); }}
First we need to create an action from the controller code: class CreateOrder { public function __construct(private CalculatePayPrice $calculatePayPrice) { } public function execute(Request $request): Order { $order = Order::create([ 'customer_name' => $request->customerName, 'net_amount' => $request->netAmount, 'pay_amount' => $request->netAmount, ]); return $this->calculatePayPrice->execute($order); }}