To address your issue of handling specific mail events without triggering the global MessageSent event, you can create custom events for each specific mail notification. This way, you can listen to these custom events instead of the global MessageSent event.
Here's a step-by-step solution:
-
Create Custom Events: Create custom events for each type of email notification you want to handle. For example, let's create an event for a notification email.
// app/Events/NotificationEmailSent.php namespace App\Events; use Illuminate\Mail\Events\MessageSent; class NotificationEmailSent extends MessageSent { // You can add additional properties or methods if needed } -
Dispatch Custom Events: Dispatch these custom events in your job or wherever you are sending the email. For example:
// app/Jobs/SendNotificationEmail.php namespace App\Jobs; use App\Events\NotificationEmailSent; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\SerializesModels; use Illuminate\Support\Facades\Mail; use App\Mail\YourMailable; class SendNotificationEmail implements ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; public function __construct() { // Constructor logic } public function handle() { $mailable = new YourMailable(); Mail::send($mailable); // Dispatch the custom event event(new NotificationEmailSent($mailable)); } } -
Listen to Custom Events: Update your
EventServiceProviderto listen to these custom events.// app/Providers/EventServiceProvider.php namespace App\Providers; use App\Events\NotificationEmailSent; use App\Listeners\NotificationEmailSentListener; use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider; class EventServiceProvider extends ServiceProvider { protected $listen = [ NotificationEmailSent::class => [ NotificationEmailSentListener::class, ], ]; public function boot() { parent::boot(); } } -
Handle Custom Events: Update your listener to handle the custom event.
// app/Listeners/NotificationEmailSentListener.php namespace App\Listeners; use App\Events\NotificationEmailSent; class NotificationEmailSentListener { public function __construct() { } public function handle(NotificationEmailSent $event): void { if (isset($event->data['notificationItems'])) { foreach ($event->data['notificationItems'] as $notificationItem) { $notificationItem->sent_at = now(); $notificationItem->save(); } } } }
By creating and dispatching custom events, you can ensure that your listeners are only triggered for the specific mail notifications you are interested in, avoiding the need to filter out unwanted events. This approach provides a cleaner and more maintainable solution.