Currently seeking new career opportunities in web development, particularly with Laravel, Hire Me

Laravel storing mailables

David Carr

Laravel Framework Tutorials PHP & MySQL

Laravel's Mailable emails are perfect for sending rich HTML emails, there are times when you need to store the contents of an email being sent out.

Here's where things get tricky. When sending a mailable the default documented approach is to create a new instance inside the send() method.

Mail::to($to)->send(new SendAlert());

That makes sense since you can see the contents of an email by returning an instance of the mailable like this:

return new SendAlert();

That does not help us storing the email, well it actually does, you see when creating an instance of the mailable it does not render directly it needs to be returned in order to be executed. That's what the send() method does.

Looking over the Mailable class there is a method called render() which renders the email. This is perfect for our needs.

Going back to my earlier example lets now create a new instance inside send() and instead pass an instance.

$mailbody = new SendAlert();
Mail::to($to)->send($mailbody);

The email will still send and now we can store the contents by calling the render method on our object.

$body = $mailbody->render();

 

Laravel Modules Your Logo Your Logo Your Logo

Become a sponsor

Help support the blog so that I can continue creating new content!

Sponsor

My Latest Book

Modular Laravel Book - Laravel: The Modular way

Learn how to build modular applications with Laravel Find out more

Subscribe to my newsletter

Subscribe and get my books and product announcements.

Learn Laravel with Laracasts

Faster Laravel Hosting

© 2006 - 2024 DC Blog. All code MIT license. All rights reserved.