Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optional parameters to Laravel Mail

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']);
        });
}
like image 881
Peder Wessel Avatar asked Oct 17 '25 19:10

Peder Wessel


1 Answers

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.

like image 131
Jeroen Noten Avatar answered Oct 20 '25 10:10

Jeroen Noten



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!