You’re correct: Filament’s RelationManager doesn’t natively call an afterCreate method on the manager itself. Instead, you typically use the form’s afterCreate() callback, but as you noted, this leads to duplication if you have many relation managers.
Solution: Use an Abstract Base RelationManager
You can create a base relation manager that all your relation managers extend. In this base class, you can define a reusable afterCreate logic and inject it into the form’s afterCreate callback for all children.
Here’s how you can do it:
// app/Filament/RelationManagers/BaseRelationManager.php
namespace App\Filament\RelationManagers;
use Filament\Resources\RelationManagers\RelationManager;
use Filament\Forms;
use Illuminate\Database\Eloquent\Model;
abstract class BaseRelationManager extends RelationManager
{
// Override this in child classes if needed
protected function afterCreate(Model $record): void
{
// Common logic here
// Example: \Log::info('Created: ' . get_class($record));
}
public static function form(Forms\Form $form): Forms\Form
{
// Call parent's form() if you want to support schema inheritance
$instance = new static(app());
$form = method_exists(get_parent_class(static::class), 'form')
? parent::form($form)
: $form;
return $form->afterCreate(function (Model $record) use ($instance) {
$instance->afterCreate($record);
});
}
}
Now, in your relation managers, extend this base class:
// app/Filament/RelationManagers/UnitsRelationManager.php
namespace App\Filament\RelationManagers;
class UnitsRelationManager extends BaseRelationManager
{
protected static string $relationship = 'units';
protected static ?string $recordTitleAttribute = 'reference';
// Optionally override afterCreate if you want custom logic for this manager
protected function afterCreate(Model $record): void
{
parent::afterCreate($record);
// Custom logic for UnitsRelationManager
// dd('here');
}
}
Key Points:
- All relation managers inherit the afterCreate logic from the base class.
- You only need to write the afterCreate logic once.
- If a specific relation manager needs custom logic, override afterCreate in that class and call parent::afterCreate($record) if you want to keep the base logic.
Note:
If you need to pass the form schema from each child, you can add an abstract method in the base class for the schema, and call it in the base form() method.
Let me know if you need an example for that!