Php 邮件发送失败时不保存数据
我有一个foreach循环,负责在将信息保存到数据库后发送邮件Php 邮件发送失败时不保存数据,php,laravel,laravel-5.5,Php,Laravel,Laravel 5.5,我有一个foreach循环,负责在将信息保存到数据库后发送邮件 foreach ($cart->items as $item){ $order->details()->create([ 'quantity' => $item['quantity'], 'discount' => $product->discount, 'total' => $total,
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循环的第一个项目,并抛出一个错误,阻止其余代码执行
在这个特定的场景中,是否有一种方法可以防止在邮件发送失败时保存数据?您是否尝试过使用数据库事务 您可以使用DB facade上的transaction方法在数据库事务中运行一组操作。如果在事务关闭中引发异常,则事务将自动回滚
虽然此链接可能会提供一些有限的、即时的帮助,但您的其他用户可能会知道它是什么,以及它为什么存在。总是引用一个重要链接中最相关的部分,以便将来读者提出其他类似问题时更有用。另外,其他用户倾向于对答案做出负面反应,而这些答案是正确的。我会将事务调用放在循环中。否则,即使第3029封电子邮件失败,您也会回滚每一位数据。如果你加上一个try/catch,那么这样做也会让其余的电子邮件继续发送。
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));
}
}