Easy and Fast Emails with Laravel 5.3 Mailables

Laravel 5.3 has just been released and there are a ton of great new features. One of the major improvements is in how you send mail in your applications.

Let’s take a look at sending emails. Before Laravel 5.3, sending emails in Laravel looked a lot like this.

Mail::send('emails.send', ['title' => $title, 'message' => $message], function ($message) { $message->from('no-reply@scotch.io', 'Scotch.IO'); $message->to('batman@batcave.io'); });

This method worked for a while, but after sending a couple of emails, the code base got messy. Since I didn’t really like this method, I found myself using event listeners to build emails.

Installing Laravel 5.3

At the time of this article, installing Laravel 5.3 with Laravel installer is as simple as.

laravel new project

Introducing Mailables

Mailables in Laravel abstracts building emails with a mailable class. Basically, mailables are responsible for collating data and passing them to views. Meanwhile, the API for sending emails got really simple.

To send emails in Laravel, all we have to do now is.

Mail::to('batman@batcave.io')->send(new KryptoniteFound);

Don’t get me wrong, the previous API will work just fine (and it will still work in your applications) — it’s just that the Mail API got a whole lot simpler.

Creating a Mailable

With artisan our super handy Laravel cli-tool, we can simply create a mailable like this.

php artisan make:mail

Since our mailable’s name is KryptoniteFound, we can create our mailable using this command.

php artisan make:mail KryptoniteFound

After we’ve created our mailable, in app/mail, we can see our newly created mailable class.

namespace App\Mail; use Illuminate\Bus\Queueable; use Illuminate\Mail\Mailable; use Illuminate\Queue\SerializesModels; use Illuminate\Contracts\Queue\ShouldQueue; class KryptoniteFound extends Mailable { use Queueable, SerializesModels; public function __construct() { // } public function build() { return $this->view('view.name'); } }

The created class should look like the snippet above (comments stripped).

As we can see, the build method builds the message. For our case, we can replace the view.name with the path to our email view email.kryptonite-found.

In resources/views create a new blade template in an email folder called kryptonite-found.blade.php.

Passing Data to Email Views


Originally published at www.laravelfeed.com.

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.