Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel: Set mail subject from mail blade template

Tags:

email

laravel

When using the Laravel 6 mail functionality, I would like to set the message subject in the email's blade template. This seems more natural to me than doing it in the Mail class itself, because whoever is maintaining the mail templates should also be able to customize the subject and use the template variables.

Example of what I am trying to accomplish:

@component('mail::subject')
Sample Message to {{ $user }}
@endcomponent

@component('mail::message')
# Sample Message

This is a sample message
@endcomponent

How could this be done?

like image 590
flexponsive Avatar asked Oct 18 '25 20:10

flexponsive


1 Answers

I struggled with this as well. It took me a while to find a decent solution but here it is:

The mailable class:

class Mailing extends Mailable {

    use Queueable;
    use SerializesModels;

   ...

    public function build() {
        return $this
            ->markdown('emails.somemailing')
            ->with('setSubject', function($subject) {   // Use to be able to set the subject from within the markdown blade
                    $this->subject($subject);
                });
    }
}

Then in the markdown blade you can call the setSubject like this:

@php
$setSubject('Hooray, it works!');
@endphp

@component('mail::message')

...

@endcomponent

PS You can also set $this->subject directly as a closure:

->with('setSubject', Closure::fromCallable([$this, 'subject']));
like image 147
Arno van Oordt Avatar answered Oct 20 '25 17:10

Arno van Oordt