[10.x] Add beforeSending
hook in Mailables
#49630
Closed
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
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, thebeforeSending
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;
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.