You can pass data from the controller to the mailable, and then from the mailable to the listener
For example I have a model called SendOrder
that I use to keep track the status of the email, so I pass this model from the controller to the listener
This is what you have to do from scratch
In your controller
Pass the model to your Mailable constructor
$send_order = SendOrder::create(['status' => 'received', 'email' => '[email protected]']); Mail::to($receiverAddress)->send(new SendNewMail($send_order));
In the Mailable SendNewMail
Class Mailable has a method withSwiftMessage()
which you can use to store variables/objects that you can access later from the listener.
We will make a constructor that pass the model to the build()
method where we can execute the withSwiftMessage()
to store it for later.
use App\SendOrder; class SendNewMail extends Mailable { protected $send_order; public function __construct( SendOrder $send_order ) { $this->send_order = $send_order; } public function build() { $send_order = $this->send_order; $this->withSwiftMessage(function ($message) use($send_order) { $message->send_order = $send_order; }); // Do more stuffs } }
Create the listener
Register the event and listener in the file app/Providers/EventServiceProvider.php
protected $listen = 'Illuminate\Mail\Events\MessageSent' => [ 'App\Listeners\LogSentMessage', ], ];
Now execute the command:
php artisan event:generate
This will automatically generate the new listener app\Listeners\LogSentMessage with a template code that’s connected to the built-in event Illuminate\Mail\Events\MessageSent
In your Listener LogSentMessage
You can access the model this way:
public function handle(MessageSent $event) { $send_order = $event->message->send_order; $send_order->update(['status' => 'sent']); }