发送邮件失败时不保存数据
Data are not saved when mail is unsuccessfully sent
我有这个 foreach
循环,负责在将信息保存到数据库后发送邮件。
foreach ($cart->items as $item){
$order->details()->create([
'quantity' => $item['quantity'],
'discount' => $product->discount,
'total' => $total,
]);
Mail::to($product->user->email)->send(new ProductOrdered($item, $order));
}
当邮件正常工作时,一切都是完美的。任何时候邮件发送失败,只保存传递给 foreach 循环的第一个项目,并抛出一个错误,阻止其余代码的执行。
在这种特殊情况下,有什么方法可以防止在邮件发送失败时保存数据?
您尝试过使用数据库事务吗?
You may use the transaction method on the DB facade to run a set of operations within a database transaction. If an exception is thrown within the transaction Closure, the transaction will automatically be rolled back.
https://laravel.com/docs/5.5/database#database-transactions
foreach ($cart->items as $item) {
DB::transaction(function () {
$order->details()->create([
'quantity' => $item['quantity'],
'discount' => $product->discount,
'total' => $total,
]);
Mail::to($product->user->email)->send(new ProductOrdered($item, $order));
}
}
我有这个 foreach
循环,负责在将信息保存到数据库后发送邮件。
foreach ($cart->items as $item){
$order->details()->create([
'quantity' => $item['quantity'],
'discount' => $product->discount,
'total' => $total,
]);
Mail::to($product->user->email)->send(new ProductOrdered($item, $order));
}
当邮件正常工作时,一切都是完美的。任何时候邮件发送失败,只保存传递给 foreach 循环的第一个项目,并抛出一个错误,阻止其余代码的执行。
在这种特殊情况下,有什么方法可以防止在邮件发送失败时保存数据?
您尝试过使用数据库事务吗?
You may use the transaction method on the DB facade to run a set of operations within a database transaction. If an exception is thrown within the transaction Closure, the transaction will automatically be rolled back.
https://laravel.com/docs/5.5/database#database-transactions
foreach ($cart->items as $item) {
DB::transaction(function () {
$order->details()->create([
'quantity' => $item['quantity'],
'discount' => $product->discount,
'total' => $total,
]);
Mail::to($product->user->email)->send(new ProductOrdered($item, $order));
}
}