Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[10.x] Add beforeSending hook in Mailables #49630

Conversation

lioneaglesolutions
Copy link
Contributor

Problem

Sometimes when sending an email, you may want to do something additional prior to the email actually being sent - such as changing the status of another model to sending or aborting if some other check fails.

Current Solution

You can put all of this in the build method of the Mailable but then that method gets quite large.

You also have access to the MessageSending event but this gives you a Symfony email where you don't have access to the Mailable properties such as any models passed in the constructor.

Proposed Solution

Similar to the configure hook in model factories, the beforeSending hook gives you the ability to perform any operations required just before the email is sent, including aborting if required.

A potential use case could be;

class InvoiceMail extends Mailable
{
    // ...

    public function beforeSending()
    {
        SystemEmail::where('owner_id', $this->invoice->id)
            ->where('owner_type', 'invoice')
            ->where('reference', $this->sendingReference)
            ->update([
                'sent_at' => Carbon::now(),
                'status' => InvoiceMailStatus::Sending,
            ]);
    }

   // ...
}

You could also do something like throw an Exception if the Invoice has already been sent but typically this might live in a wrapping job.

@taylorotwell
Copy link
Member

Thanks for your pull request to Laravel!

Unfortunately, I'm going to delay merging this code for now. To preserve our ability to adequately maintain the framework, we need to be very careful regarding the amount of code we include.

If possible, please consider releasing your code as a package so that the community can still take advantage of your contributions!

If you feel absolutely certain that this code corrects a bug in the framework, please "@" mention me in a follow-up comment with further explanation so that GitHub will send me a notification of your response.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants