diff --git a/README.md b/README.md index addc5c2..c27799c 100644 --- a/README.md +++ b/README.md @@ -263,6 +263,44 @@ By default, the package does not store the content of sent out emails. By settin SENDS_STORE_CONTENT=true ``` +### Customize Attributes stored in Send Models + +If you need to store more attributes with your `Send`-model, you can extend the `StoreOutgoingMailListener` and override the `getSendAttributes`-method. + +For example, let's say we would like to store an `audience`-value with each sent out email. We create a new Event Listtener called `CustomStoreOutgoingMailListener` and use the class a as Listener to the `MessageSent`-event. + +Our `EventServiceProvider` would look like this. + +```php +// app/Providers/EventServiceProvider.php +protected $listen = [ + // ... + \Illuminate\Mail\Events\MessageSent::class => [ + \App\Listeners\CustomStoreOutgoingMailListener::class, + ], +] +``` + +The Listener itself would look like the code below. We extend `Wnx\Sends\Listeners\StoreOutgoingMailListener` and override `getSendAttributes`. We merge the `$defaultAttributes` with our custom attributes we want to store. In our example we store an `audience` value. + +```php + $this->getAudience($event), + ]); + } +``` + ### Prune Send Models By default, `Send`-models are kept forever in your database. If your application sends thousands of emails per day, you might want to prune records after a couple of days or months. diff --git a/src/Listeners/StoreOutgoingMailListener.php b/src/Listeners/StoreOutgoingMailListener.php index 9d79546..93b4e6a 100644 --- a/src/Listeners/StoreOutgoingMailListener.php +++ b/src/Listeners/StoreOutgoingMailListener.php @@ -26,7 +26,20 @@ public function handle(MessageSent $event): void protected function createSendModel(MessageSent $event): Send { - return config('sends.send_model')::create([ + return config('sends.send_model')::forceCreate( + $this->getSendAttributes($event, $this->getDefaultSendAttributes($event)) + ); + } + + protected function getSendAttributes(MessageSent $event, array $defaultAttributes): array + { + // Implement this method in your own application to override the attributes stored in the Send Model. + return $defaultAttributes; + } + + protected function getDefaultSendAttributes(MessageSent $event): array + { + return [ 'uuid' => $this->getSendUuid($event), 'mail_class' => $this->getMailClassHeaderValue($event), 'subject' => $event->message->getSubject(), @@ -37,7 +50,7 @@ protected function createSendModel(MessageSent $event): Send 'cc' => $this->getAddressesValue($event->message->getCc()), 'bcc' => $this->getAddressesValue($event->message->getBcc()), 'sent_at' => now(), - ]); + ]; } protected function getSendUuid(MessageSent $event): ?string