Prince Lionel N'zi
Prince Lionel N'zi

Reputation: 2588

Data are not saved when mail is unsuccessfully sent

I have this foreach loop which is responsible of sending a mail after saving the information to the database.

    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));
    }

When the mail works fine, everything is perfect. Anytime the mail fails to be sent, only the first item passed to the foreach loop is saved, and an error is thrown which prevent the rest of the code from executing.

In this particular scenario, is there a way for me to prevent the the data from being saved anytime the mail fails to be sent ?

Upvotes: 0

Views: 94

Answers (1)

suxur
suxur

Reputation: 205

Have you tried using database transactions?

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));
    }
}

Upvotes: 1

Related Questions