
本文介绍如何在 laravel 控制器中通过数据库事务(db::begintransaction)实现多个模型的批量插入或更新,确保所有操作要么全部成功,要么全部回滚,避免数据不一致问题。
本文介绍如何在 laravel 控制器中通过数据库事务(db::begintransaction)实现多个模型的批量插入或更新,确保所有操作要么全部成功,要么全部回滚,避免数据不一致问题。
在 Laravel 应用中,当一个业务逻辑需要同时创建或更新多个关联模型(如 Loan、AssignLoan、TransactionReport 等)时,若缺乏统一的错误控制机制,极易出现“部分成功、部分失败”的数据不一致状态——例如前两个模型已保存,第三个因验证或外键约束失败而中断,导致系统状态不可逆地偏离预期。
解决方案:使用数据库事务(Database Transaction)
Laravel 基于 PDO 提供了完整的事务支持,通过 DB::beginTransaction()、DB::commit() 和 DB::rollBack() 可精确控制操作边界。所有 Eloquent 模型操作(包括 save()、update()、create() 等)在事务开启后均处于同一上下文,任一环节抛出异常都会触发回滚,保障数据强一致性。
✅ 正确改造示例(基于原 store 方法):
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
public function store(Request $request)
{
$this->authorize('loans.create');
$validated = $this->validate($request, [
'loan_id' => 'required|numeric',
'received_by' => 'required|string|max:100',
'received_amount' => 'required|numeric',
'deposit' => 'nullable|numeric',
'deposit_1' => 'nullable|numeric',
'installments' => 'required|numeric',
'date' => 'required|date',
'total_amount' => 'required|numeric',
]);
try {
DB::beginTransaction();
// 1. 创建 Loan 记录
$loan = Loan::create([
'loan_id' => $validated['loan_id'],
'received_by' => $validated['received_by'],
'received_amount' => $validated['received_amount'],
'deposit' => $validated['deposit'] ?? 0,
'deposit_1' => $validated['deposit_1'] ?? 0,
'installments' => $validated['installments'],
'date' => $validated['date'],
'Txn' => Str::random(10),
'total_amount' => $validated['total_amount'],
'somity_id' => auth()->user()->mst_somity_id,
'is_active' => 1,
]);
// 2. 更新 AssignLoan 关联记录
$assignLoan = AssignLoan::findOrFail($validated['loan_id']);
$assignLoan->deposit += $validated['deposit'] ?? 0;
$assignLoan->deposit_1 += $validated['deposit_1'] ?? 0;
$assignLoan->paid_amount += $validated['received_amount'];
$assignLoan->remaining_amount = $assignLoan->total_amount - $validated['received_amount'];
$assignLoan->save();
// 3. 创建 TransactionReport
$customer_id = $assignLoan->assignloan?->customer_id
?? $assignLoan->customer?->id
?? throw new \Exception('Customer ID not found for loan assignment.');
TransactionReport::create([
'transaction_type' => 'loan_received',
'customer_id' => $customer_id,
'transaction_description' => 'loan received with deposit',
'transaction_method' => 'cash',
'transaction_amount' => $validated['total_amount'],
'transaction_date' => $validated['date'],
'transaction_time' => now()->format('H:i:s'),
'transaction_by' => $validated['received_by'],
'somity_id' => auth()->user()->mst_somity_id,
'created_user_id' => auth()->id(),
'is_loan_diposite' => $loan->id,
'Txn' => $loan->Txn,
]);
// ✅ 所有操作成功,提交事务
DB::commit();
// 4. 发送短信(注意:此操作应置于事务外,避免阻塞或依赖 DB 连接)
$this->sendLoanSms($assignLoan, $validated);
$notification = ['message' => 'Loan added successfully.', 'alert-type' => 'success'];
return redirect()->route('loan.index')->with($notification);
} catch (\Exception $e) {
// ❌ 任意环节失败,回滚全部变更
DB::rollBack();
\Log::error('Loan store transaction failed', [
'exception' => $e->getMessage(),
'trace' => $e->getTraceAsString()
]);
$notification = [
'message' => 'Failed to process loan: ' . $e->getMessage(),
'alert-type' => 'error'
];
return back()->withInput()->with($notification);
}
}
// 独立方法处理短信发送(非事务内)
protected function sendLoanSms($assignLoan, $data)
{
$adminSettings = AdminSeetings::where('somity_id', auth()->user()->mst_somity_id)->first();
if (!$adminSettings || $adminSettings->automatic_sms != 1) return;
$smsPackage = SmsPackageAssignToSomity::where('somity_id', auth()->user()->mst_somity_id)->first();
if (!$smsPackage || $smsPackage->remaining_sms <= 0) return;
$customerPhone = $assignLoan->customer?->customer_phone;
if (!$customerPhone) return;
$message = "Your loan No: {$assignLoan->loan_number}. received amount: {$data['received_amount']} Tk. Remaining Balance: {$assignLoan->remaining_amount} Tk.";
// 实际调用 API(建议改用队列异步执行)
$url = "https://bulksms.aloitltd.com/services/send.php?key=" . env('API_KEY') .
"&number={$customerPhone}&message=" . urlencode($message) .
"&option=" . env('OPTION') . "&type=" . env('TYPE') . "&prioritize=" . env('PRIORITIZE');
// ⚠️ 注意:此处不应直接重定向到外部 URL;应使用 HTTP 客户端(如 Guzzle)发起请求
// Redirect::to($url) 是错误用法,会导致响应中断且无法捕获结果
// 更新短信用量(同样需事务保护 —— 若短信发送成功但用量未更新,可接受补偿逻辑)
$smsPackage->decrement('remaining_sms');
$smsPackage->increment('use_sms');
$smsPackage->save();
}? 关键注意事项:
- 事务仅作用于数据库操作:HTTP 重定向、文件写入、第三方 API 调用等不可回滚,必须移出事务块。
- 避免在事务中执行耗时操作(如发短信、邮件),否则会延长锁持有时间,影响并发性能;推荐使用 Laravel 队列异步处理。
-
务必捕获
\Exception或更具体的异常类(如QueryException,ModelNotFoundException),而非静默忽略。 -
日志记录不可少:
DB::rollBack()后应记录完整错误上下文,便于排查。 -
关联查询需谨慎:如
$assignLoan['customer']['customer_phone']使用数组访问易报错,应改用 Eloquent 关系访问($assignLoan->customer->customer_phone)并配合空值检查或optional()辅助函数。
通过合理运用数据库事务,你不仅能保证核心业务数据的一致性与可靠性,也为后续审计、对账及系统扩展打下坚实基础。


















