Keith Sorbo
Keith Sorbo

Reputation: 25

Laravel Send or Queue Mail depending on config setting

I am looking for a neat way to send or queue email depending on a config setting.

Right now I am having to do something like this everytime I send an email

$mailContent = new AccountNotification($account);
$mailObject = Mail::to($email);
if(config('app.queueemail')){
   $mailObject->queue($mailContent);
} else {
   $mailObject->send($mailContent);
}

There has to be a simpler way to do this so I don't have to repeat this code each time I want to send an email.

Upvotes: 0

Views: 74

Answers (1)

Mozammil
Mozammil

Reputation: 8750

Extending @ceejayoz's comment, a simpler way could also be to use a global Helper function.

For example, you could have a send_email() global function that will send/queue email depending on your app's configuration.

if ( ! function_exists('send_email')) {
    /**
    * Sends or queues email
    *
    * @return mixed
    */
    function send_email($mailer, $content)
    {
        return config('app.queueemail')
            ? $mailer->queue($content)
            : $mailer->send($content); 
    }
}

To use it you would do:

send_email($mailer, $content); 

Upvotes: 2

Related Questions