Run Jobs Instantly in Laravel Using dispatch_sync()
Laravel’s dispatch_sync() helper allows developers to execute jobs immediately within the current request. This article explains when and why to use dispatch_sync() with a real-world project example.
Real Project Example: Inventory Stock Update
Imagine an e-commerce application where stock must be updated instantly after an order is placed.
Delaying this update could cause:
- Overselling
- Incorrect stock display
- Order conflicts
Instead of placing logic directly in the controller, use a job — but run it synchronously.
dispatch_sync(new UpdateProductStock(
productId: $order->product_id,
quantity: $order->quantity
));
Now:
- Stock updates immediately
- Business logic stays inside a job
- Code remains clean and testable