Prodigle
Prodigle

Reputation: 1797

Laravel polymorphic relationship 0 results

I have a polymorphic relationship with Laravel. My polymorphic relationship is Message->messageable becoming either Group or Chat.

Going from Message->messageable will give me the proper result(e.g the group or chat the message is associated with).

Going from example Group::first()->with('messages')->get() will return an empty messages array.

My db tables for message are messageable_id messageable_type

My model methods are as follows

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

^works as intended

class Group extends Model
{
function messages(){
    return $this->morphMany('Message','messageable');
}

class Chat extends Model
{
public function messages(){
    return $this->morphMany('Message','messageable');

These return empty.

example data used: 1

Any ideas?

Upvotes: 1

Views: 383

Answers (2)

Prodigle
Prodigle

Reputation: 1797

Forgot to include namespaces in my Database messageable_type.

Changed from Group to App\Group.

Upvotes: 1

fubar
fubar

Reputation: 17378

You relationships are incorrect. You need to reference the full class namespace, not just the class name itself. E.g.

class Group extends Model
{
    public function messages()
    {
        return $this->morphMany(\App\Models\Message::class', 'messageable');
    }
}

Upvotes: 1

Related Questions