mvanduijker / laravel-transactional-mails
Send mails after DB transaction is committed
Installs: 4 983
Dependents: 0
Suggesters: 0
Security: 0
Stars: 6
Watchers: 1
Forks: 0
Open Issues: 0
Requires
- php: ^7.3|^8.0
- illuminate/database: ~6.0,!=6.9.0|~7.0|~8.0|~9.0|~10.0|~11.0
- illuminate/mail: ~6.0|~7.0|~8.0|~9.0|~10.0|~11.0
Requires (Dev)
- larapack/dd: ^1.0
- orchestra/testbench: ~4.0|~5.0|~6.0|~7.0|~8.0|~9.0
- phpunit/phpunit: ^9.3|^10.0
This package is auto-updated.
Last update: 2024-10-13 21:40:31 UTC
README
Send your mails after database transaction is committed.
This package prevents for e-mails being sent within a transaction when the transaction fails. It will buffer the emails (or queued emails) and sends (or queues) them after the transaction is committed. Especially sending emails in the background within a transaction and the job picks up the email before the transaction has committed the job might retrieve invalid data.
Installation
You can install the package via composer:
composer require mvanduijker/laravel-transactional-mails
Usage
You only have to extend your mailable with Duijker\LaravelTransactionalMails\TransactionalMailable
instead of Illuminate\Mail\Mailable
.
<?php namespace App\Mail; use App\Order; use Duijker\LaravelTransactionalMails\TransactionalMailable; use Illuminate\Bus\Queueable; use Illuminate\Queue\SerializesModels; class OrderShipped extends TransactionalMailable { use Queueable, SerializesModels; /** * The order instance. * * @var Order */ protected $order; /** * Create a new message instance. * * @return void */ public function __construct(Order $order) { $this->order = $order; } /** * Build the message. * * @return $this */ public function build() { return $this->view('emails.orders.shipped') ->with([ 'orderName' => $this->order->name, 'orderPrice' => $this->order->price, ]); } }
<?php namespace App\Http\Controllers; use App\Order; use App\Mail\OrderShipped; use Illuminate\Http\Request; use Illuminate\Support\Facades\Mail; use App\Http\Controllers\Controller; class OrderController extends Controller { /** * Ship the given order. * * @param Request $request * @param int $orderId * @return Response */ public function ship(Request $request, $orderId) { $order = Order::findOrFail($orderId); DB::transaction(function () use ($order, $request) { $order->ship(); Mail::to($request->user())->send(new OrderShipped($order)); throw new \RuntimeException('Mail won\'t be sent'); }); } }
Testing
composer test
Changelog
Please see CHANGELOG for more information on what has changed recently.
Contributing
Please see CONTRIBUTING for details.
Credits
License
The MIT License (MIT). Please see License File for more information.