Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

natcave's avatar
Level 10

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

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!

0 likes
3 replies
yassineqoraiche's avatar

You can append values to the underlying swift mail class in your mailable.

Create a new mailable class to extend the parent Mailable

<?php
    // App/Mail/Mailable.php

namespace App\Mail;

use Illuminate\Contracts\Mail\Mailer as MailerContract;
use Illuminate\Mail\Mailable as BaseMailable; // Extend off laravel mailable

abstract class Mailable extends BaseMailable
{
    public function send(MailerContract $mailer)
    {
        //Initializes properties on the Swift Message object
        $this->withSwiftMessage(function ($message) {
            $message->mailable = get_class($this);
        });

        parent::send($mailer);
    }
}

in your mailable classes replace the mailable class with the one we create:

use App\Mail\Mailable;
// use Illuminate\Mail\Mailable;

Now, the mailable name parameter is available in your $event->message object:

// App\Listeners\LogMessageSending.php
public function handle(MessageSending $event)
{

  dd($event->message->mailable);

}
razvanC's avatar

Anyone has some idea on how to do this now please ? Seems $message->mailable = get_class($this); returns a closure now thus can't access $even->message->mailable anymore in the listener.

Please or to participate in this conversation.