0

Currently in our system I send emails by using the laravel mailables like so

Mail::to($user)->send(new AccountCreation($user))

This works as intended however in our system we have some complex global rules for when to send an email to a person that should be used everywhere, for example:

if ($user->isActive) {
    Mail::to($user)->send(new AccountCreation($user));
}

I do not want to check the user every time and would rather the mailable logic handle this.

Is there a clean way to handle global rules for when to send an email?

Tom Headifen
  • 1,885
  • 1
  • 18
  • 35

1 Answers1

0

Make a mail() function in the User model and insert your global rules for all users. So instead of calling:

Mail::to($user)->send(new AccountCreation($user))

You'll be calling:

$user->mail(new AccountCreation($user))

You can make your mail function as follows:

class User extends Model {
    (...)
    public function mail(Mailer $mailer) {
        if ($this->isActive) {
            Mail::to($this)->send($mailer);
        }
    }
    (...)
}
  • Hi Andre. Thanks for your answer however looking at the link I commented it seems overwriting the the `MailServiceProvider` is a more elegant way to handle this problem. – Tom Headifen Aug 13 '18 at 15:05
  • Hi @hdifen I don't agree with you. As a rule that only addresses the `User` model, it should be inside it. – André Piva Aug 15 '18 at 04:30