Skip to content

Commit

Permalink
Added overload function for allowing dynamic properties
Browse files Browse the repository at this point in the history
  • Loading branch information
LewBlu committed Jun 4, 2024
1 parent bd2517f commit c9bb799
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
20 changes: 20 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,26 @@ class WelcomeMail extends TemplateMailable

By extending the `\Spatie\MailTemplates\TemplateMailable` class this mailable will be rendered using the corresponding `MailTemplate`. All public properties on the `WelcomeMail` will be available in the template.

If you need to use properties within your template that are initially defined within your `WelcomeMail` (for example, data that comes from another source). You can call `$this->setAdditionalData()` and pass it an array of you additional key => value pairs.

An example of this would be:
```php
namespace App\Mail;

use TemplateMailable;

class WelcomeMail extends TemplateMailable
{

public function __construct(User $user)
{
$this->setAdditionalData([
'name' => 'Joe Bloggs'
]);
}
}
```

### Customizing the `MailTemplate` model

The default `MailTemplate` model is sufficient for using _one_ database mail template for _one_ mailable. If you want to use multiple mail templates for the same mailable _or_ extend the `MailTemplate` model, we highly encourage you to publish the `mail_template` migration and create your own mail template model by extending `MailTemplate`. Make sure to implement the `MailTemplateInterface` interface as well.
Expand Down
16 changes: 16 additions & 0 deletions src/TemplateMailable.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,9 @@ abstract class TemplateMailable extends Mailable
/** @var MailTemplateInterface */
protected $mailTemplate;

/** @var array */
protected $additionalData;

public static function getVariables(): array
{
return static::getPublicProperties();
Expand Down Expand Up @@ -111,4 +114,17 @@ protected function getMailTemplateRenderer(): TemplateMailableRenderer
{
return app(TemplateMailableRenderer::class, ['templateMailable' => $this]);
}

public function buildViewData(): array
{
$mailablePropeties = parent::buildViewData();
if(is_null($this->additionalData)) {
return $mailablePropeties;
}
return array_merge($mailablePropeties, $this->additionalData);
}

public function setAdditionalData($array) {
$this->additionalData = $array;
}
}

0 comments on commit c9bb799

Please sign in to comment.