Categories
Laravel Development

Laravel Mailable – how to add subject to email

Sending email in Laravel is simple, and is based on few steps, assuming that some mail provider (like SendGrid for instance) is already set in .env file.

  1. install Maillable module for some specific type of email you would like to send:

    php artisan make:mail NotificationEmail -m emails.notificationEmail

  2. the above produces mailable class:  App/Mail/NotificationEmail.php and mail template at view/emails/notificationEmail.blade.php.
  3. now you can send email:
use App\Mail\PaymentConfirmation;
use Illuminate\Support\Facades\Mail;

$email_to = 'example@example.com';
Mail::to($email_to)->send(new EmailNotification());

It means, more or less, that you have to create mailables for every type of email, which has some advantages. The problem only is, that just after creation Laravel uses default email subject based on mailable class name. In mailable class below you will find method build, where you can configure from, subject, view and attach :

public function build()
    {
        return $this->subject('write your subject here')
            ->markdown('emails.notificationEmail');
    }

but just after creation you are set with view/markdown only. Above we can see how we can modify subject – BUT, it will be the same for all new emails of this type. To make subject dynamic, we have to inject information about new subject to the mailable somehow. It can be done by mailable class modification – we have to add to the class property $emailSubject and make it as parameter for the class constructor:

public $emailSubject;

public function __construct($emailSubject)
{
    $this->emailSubject = $emailSubject;
}

public function build()
{
    return $this->subject($this->emailSubject)
                ->markdown('emails.notificationEmail');
}

Now we can accept subject text dynamically:

use App\Mail\PaymentConfirmation;
use Illuminate\Support\Facades\Mail;

$email_to = 'example@example.com';
$subject = 'This is a Notification Email';
Mail::to($email_to)->send(new EmailNotification($subject));

Actually, by using mailable option with and adding public $data property to Mailable class NotificationEmail you can also pass some variables included in $data (can be array) through class constructor, so they are available on emailNotification.blade.php template. It makes the template customised on the fly (order id, or some other data):

public function build()
    {
        return $this->subject($this->emailSubject)
              ->with(['data', $this->data])
            ->markdown('emails.notificationEmail');
    }

 
Obviously, we need to update __construct accordingly:

public $emailSubject;
public $data;

public function __construct($emailSubject,$data)
{
    $this->emailSubject = $emailSubject;
    $this->data = $data;
}