LibraryITforGood
LibraryITforGood
FFilament
Created by LibraryITforGood on 5/13/2024 in #❓┊help
Reuse code for afterCreate and afterSave in multiple Resources
I have multiple resources that after a record is created or edited sends a email or emails depending on what the user has done with the record. I would like to reuse as much as the logic as possible as currently I duplicate all the code on each of the create and edit pages, but I am not sure how, or where to put the code. For example in EntryResource and ManageResource. When a user Creates a record or Edits a record in either of those resources several emails are sent, with a bunch of if and elseif statements to determine which email should be sent and to whom. On EntryResource/Pages/CreateNew.php
public function afterCreate(): void
{

$field1 = $this->record->field1;
$field2 = $this->record->field12;

if ($field1 == 'Done') {
Mail::to('[email protected]')
->send(new Email(
$field3, $field4));

elseif ($field1 == 'NotDone') {
Mail::to('[email protected]')
->send(new OtherEmail(
$field3, $field4));
}
public function afterCreate(): void
{

$field1 = $this->record->field1;
$field2 = $this->record->field12;

if ($field1 == 'Done') {
Mail::to('[email protected]')
->send(new Email(
$field3, $field4));

elseif ($field1 == 'NotDone') {
Mail::to('[email protected]')
->send(new OtherEmail(
$field3, $field4));
}
On Resource/Pages/EditNew.php
public function afterSave(): void
{

$field1 = $this->record->field1;
$field2 = $this->record->field12;

if ($field1 == 'Done') {
Mail::to('[email protected]')
->send(new Email(
$field3, $field4));

elseif ($field1 == 'NotDone') {
Mail::to('[email protected]')
->send(new OtherEmail(
$field3, $field4));
}
public function afterSave(): void
{

$field1 = $this->record->field1;
$field2 = $this->record->field12;

if ($field1 == 'Done') {
Mail::to('[email protected]')
->send(new Email(
$field3, $field4));

elseif ($field1 == 'NotDone') {
Mail::to('[email protected]')
->send(new OtherEmail(
$field3, $field4));
}
The same code above is duplicated on ManageResource CreateNew.php and EditNew.php. So, is there a place that I can put the code that all the resources could point to? I thought about a controller, but I read Filament doesn't use those. The code does work if I have it on each page, I am just looking to reduce the length of all of the pages and the files I need to change if there is an update. Right now I am changing fourteen pages if there is an update, which is just enough to bring in errors or a missed document. I am using FilamentPHP v3 on Laravel 10 and know just enough to be dangerous. Thanks for any suggestions or help!
7 replies