How to add a (polymorphic) relationship to a model using a trait?

Is there a way to add a relationship to a model using a trait without overwriting the existing relationships in the models the trait is being added to?

Imagine you want to add comments to multiple models, so you create a Comment model and you would probably want to create a polymorphic One to Many relationship. The preferred solution would be to have something like an IsCommentable trait where you define the relationship once.

In Laravel, that would look like this:

trait IsCommentable
{
    public function comments(): MorphMany
    {
        return $this->morphMany(Comment::class, 'commentable');
    }
}

Of course in October CMS, you need to use the $morphMany property, but you can’t do that in a trait because it would overwrite the existing $morphMany property in the models you are adding your IsCommentable trait to.

So is anyone aware of a way to accomplish something like this in October CMS?

Hi @fj82

Hook the “initialize” constructor for the trait, something like this:

/**
 * initializeIsCommentable constructor
 */
public function initializeIsCommentable()
{
    $this->morphMany['commentable'] = Comment::class; 
}

Perfect, thanks! I didn’t know about trait initializers yet.