Is there a better way to reference the Mailable class name when MessageSending event fires?

Posted 1 year ago by natcave

I'm building an email log table. One of the fields will store the name of the mailable class, for example ""App\Mail\Welcome". The idea is I want to be able to track how many times an email was sent so that automating emails will prevent sending the same email type more than once.

The way I did it was to store the mailable class name in the build function like so:

Mail\Welcome.php

class Welcome extends Mailable

public function build()
{
    $mailable = get_class($this);
    return $this->markdown('emails.welcome')->subject("Welcome.")
            ->with(compact('mailable'));
}

Then, in Listeners\LogSendingMessage.php

// Check for Mailable
if (isset($event->data['mailable'])) {
    Log::info("Mailable: " . $event->data['mailable']);
}               

This works, however I would need to add $mailable = get_class($this); to every Mailable. Is there a way of accessing the Mailable class name directly from the event?

Thanks in advance!

Please sign in or create an account to participate in this conversation.