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?
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']));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With