Create optional message parts to Laravel's Mail function?
E.g. either adding attachment or having bcc.
Mail::send('emails.welcome', $data, function($message)
{
$message->from('[email protected]', 'Laravel');
$message->to('[email protected]')->cc('[email protected]');
$message->attach($pathToFile); <========= OPTIONAL =========
});
I REALLY want to avoid ugly code like this
if (isset($data['attachment'])) {
// Attachment
Mail::queue('emails.raw', ['content' => $content], function($message) use ($data) {
$message
->subject($data['subject'])
->attach($data['attachment'])
->to($data['email'])
->bcc($data['bcc']);
});
}
else{
// No attachment
Mail::queue('emails.raw', ['content' => $content], function($message) use ($data) {
$message
->subject($data['subject'])
->to($data['email'])
->bcc($data['bcc']);
});
}
You can just move the if condition into the closure:
Mail::queue('emails.raw', ['content' => $content], function($message) use ($data) {
$message
->subject($data['subject'])
->to($data['email'])
->bcc($data['bcc']);
if (isset($data['attachment'])) {
$message->attach($data['attachment']);
}
});
Note that the chaining of methods just syntactical sugar. The above is equivalent to:
Mail::queue('emails.raw', ['content' => $content], function($message) use ($data) {
$message->subject($data['subject']);
$message->to($data['email']);
$message->bcc($data['bcc']);
if (isset($data['attachment'])) {
$message->attach($data['attachment']);
}
});
So write it however you like.
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