How to create global rules for when to send an email

34
August 11, 2018, at 09:20 AM

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?

Answer 1

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(your, custom, attributes, here)

Or even a custom function for each type of email, such as:

$user->mailAccountCreation()

You can make your mail function as

class User extends Model {
    (...)
    public function mailAccountCreation() {
        if ($this->isActive) {
            Mail::to($this)->send(new AccountCreation($this));
        }
    }
    (...)
}
READ ALSO
rewrite using array filter

rewrite using array filter

How would I write the following foreach with some conditions using array_filter?

38
How is it that the route logic can modify the behaviour of a dropdown menu made with a @foreach?

How is it that the route logic can modify the behaviour of a dropdown menu made with a @foreach?

I'm stumped on a very simple issue but all what I've tried so far is uselessTo start with, I'm a total rookie on his way to learn how to code with Laravel 5

27
Insert sql query isn't working, why? [duplicate]

Insert sql query isn't working, why? [duplicate]

This question already has an answer here:

34
Modifying the keys in a PHP array before sending to JSON

Modifying the keys in a PHP array before sending to JSON

I am querying a SQL database and returning some valuesWhat I have is Field1 and Field2 which come out with a list of dates (There may be up to 200 values/dates eventually)

53