返回 Skill 列表
extension
分类: 开发与工程无需 API Key

laravel:transactions-and-consistency

将多写操作封装在事务中;使用dispatchAfterCommit和幂等性模式来确保一致性

person作者: jakexiaohubgithub

Transactions and Consistency

Ensure multi-step changes are atomic; make retries safe.

Commands

DB::transaction(function () use ($order, $payload) {
    $order->update([...]);
    $order->items()->createMany($payload['items']);
    OrderUpdated::dispatch($order);        // or flag for after-commit
});

// Listener queued after commit
class SendInvoice implements ShouldQueue {
    public $afterCommit = true;
}

Patterns

  • Use DB::transaction to wrap write sequences and related side-effects
  • Prefer $afterCommit or dispatchAfterCommit() for events / jobs
  • Make jobs idempotent (check existing state, use unique constraints)
  • Use lockForUpdate() for row-level coordination when needed
  • Validate invariants at the boundary before starting the transaction