Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

AliRezaBeitari's avatar

Multiple morphTo

Hi! I want to create Message model which has from, to, text and conversation fields. Fields from and to can be a Admin or User or Member model. Filed conversation can be null which means it's just a single message, or can be a Conversation model which means it's a message of a conversation. Filed text is just a text!

I'm not sure how to implement these! Do I need to use Polymorphic Relations?

Sorry for bad English. Thanks!

0 likes
8 replies
staudenmeir's avatar

Yes, you need MorphTo relationships for from and to and two columns each.

Schema::create('messages', function (Blueprint $table) {
    [...]
    $table->morphs('from');
    $table->morphs('to');
    [...]
});

class Message extends Model {
    public function from() {
        return $this->morphTo();
    }

    public function to() {
        return $this->morphTo();
    }
}
1 like
AliRezaBeitari's avatar

@staudenmeir I did this to, but the problme is how to associate Admin, User, Member models to it?

If I do Admin::first()->messageFromMe()->save($message) it will complain about field to beeing null!

staudenmeir's avatar
Level 24

Use associate():

$message = new Message([...]);
$message->from()->associate(Admin::find(1));
$message->to()->associate(User::find(2));
$message->save();
2 likes
staudenmeir's avatar

How did you define the messagesFromMe relationship?

1 like
AliRezaBeitari's avatar

@staudenmeir

public function messagesFromMe()
    {
        return $this->morphMany(Message::class, 'from');
    }

    public function messagesToMe()
    {
        return $this->morphMany(Message::class, 'to');
    }
staudenmeir's avatar

What's the result of dd(Admin::first()->messagesFromMe()->toSql());?

AliRezaBeitari's avatar

@staudenmeir How stupid I am!! I should use Admin::first()->messagesFromMe; not Admin::first()->messagesFromMe()!!

Thank you for your help!

Please or to participate in this conversation.