
I write beautiful code for a sad world. Former student-athlete from State College, PA. CTO, Full-stack Software Engineer. @laravelphp & @vuejs
- Tweets4.8K
- Following479
- Followers231
- Likes3K
![// ❌ Don't do this, potental for race conditions! $payment = Payment::find($paymentId); $order = Order::find($orderId); $payment->update(['status' => 'PAID']); $order->update(['status' => 'PLACED']); SendPaymentReceivedEmail::dispatch($payment->id); /* ------ */ // ✅ Instead, lock the rows & do a DB transaction \DB::transaction(function() { // Acquire a write lock for payment & order $payment = Payment::where('id', $paymentId)->lockForUpdate()->first(); $order = Order::where('id', $orderId)->lockForUpdate()->first(); // Idempotency guard, don't process it twice if ($payment->status === 'PAID') return; // Perform updates $payment->update(['status' => 'PAID']); $order->update(['status' => 'PLACED']); // Only after a successful commit we notify the user DB::afterCommit(fn () => SendPaymentReceivedEmail::dispatch($payment->id) ); });](https://pbs.twimg.com/media/G5tXXROWgAAB5hu.jpg?name=small&format=webp)
ALT // ❌ Don't do this, potental for race conditions! $payment = Payment::find($paymentId); $order = Order::find($orderId); $payment->update(['status' => 'PAID']); $order->update(['status' => 'PLACED']); SendPaymentReceivedEmail::dispatch($payment->id); /* ------ */ // ✅ Instead, lock the rows & do a DB transaction \DB::transaction(function() { // Acquire a write lock for payment & order $payment = Payment::where('id', $paymentId)->lockForUpdate()->first(); $order = Order::where('id', $orderId)->lockForUpdate()->first(); // Idempotency guard, don't process it twice if ($payment->status === 'PAID') return; // Perform updates $payment->update(['status' => 'PAID']); $order->update(['status' => 'PLACED']); // Only after a successful commit we notify the user DB::afterCommit(fn () => SendPaymentReceivedEmail::dispatch($payment->id) ); });







































