dmeganoski
3 years ago
2023
10
Laravel

Laravel 5.3 - Using Mailable inside a Notification

Posted 3 years ago by dmeganoski

While reading up on the new features in Laravel 5.3, one of my first thoughts was to question whether the mailable class could be used in conjunction with the notification class. It can! but it took me a while to figure out why it wasn't working as expected, so I'm here to share my thoughts (this may be a bug)

The simplified MailMessage class (as far as I have found) is somewhat limiting. I often have a custom email template editor built into the GUI, and the Mailable class seems like the perfect place to store the logic to check for a custom template in the database before using the default blade template.

What I am doing in this particular case is sending both an email and sms to a user which is stored in a secondary, non-authenticated table. (does not have site access). I use the 'Notifiable' trait on the model (call them customers) and use the $customer->notify(new CustomerNotification) function.

In doing this with the simplified MailMessage class, the 'to' address is automatically resolved, because of the 'email' field on the Notifiable Customer model.

When returning an instance of Mailable instead of MailMessage, however, the address was not automatically resolved, and the mail failed silently. I believe that this is a bug, that it should automatically resolve the address, but I'm not sure.

Since I was already passing an instance of my Customer class to the Mailable constructor, I used $this->to($customer->email, $customer->name) in the build function of the Mailable class to resolve this issue.

Hope this helps someone else.

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