1
votes

My app flow looks like this:

  1. I created an invoice, invoice status = created
  2. I send it to user, I use Queueable so the process of sending email is separated from main app.
  3. After sending email complete, invoice status should be sent

The problem is, I could not find any event like AfterEmailSent for specific Mailable class in app/Mail.

1

1 Answers

1
votes

You will need to create your own event, first create one:

php artisan make:event InvoiceEmailSentEvent

inside Events\InvoiceEmailSentEvent.php add the following:

 public $invoice;

 public function __construct($invoice)
    {
        $this->invoice = $invoice;
    }

Create a listener for the event:

php artisan make:listener InvoiceEmailSentListener

For the handle() function inside Listeners\InvoiceEmailSentListener.php add

//import your Mailable up here

public function handle(InvoiceEmailSentEvent $event)
    {

        // You don't have to sent email here, but I just added it if $invoice contains an email field
        $email = $event->invoice->email;
        Mail::to($email)->send(new Your_Mailable_Class_Goes_Here($event->invoice));
       // UPDATE INVOICE STATUS HERE
    }

Register your event and listener within the $listen array in App\Providers\EventServiceProvider.php

  'App\Events\InvoiceEmailSentEvent' => [
            'App\Listeners\InvoiceEmailSentListener',
        ],

Finally, in your controller you can call the Event, passing your invoice you want to update, for example

 $invoice = Invoice::findOrFail($invoice_id)->first();
 event(new InvoiceEmailSentEvent($invoice));