Support the ongoing development of Laravel.io →
posted 10 years ago
Eloquent

So I have MyApp\Posts\Post MyApp\Videos\Video

In each I declare a $morphClass of 'Post' and 'Video' respectively, so that the namespace isn't included in commentable_type field in the database

They both have this method:

public function comments()
{
    return $this->morphMany('MyApp\Comments\Comment', 'commentable');
}

I can get $post->comments() with no problem, this relationship works fine as long as $morphClass is declared to tell it to only expect 'Post' or 'Video' rather than 'MyApp\Posts\Post' or 'MyApp\Videos\Video'.

The problem is the inverse. In the Comment class I have:

public function commentable()
{
    return $this->morphTo();
}

but when I call $post->comments()->first()->commentable() I'll get an error: Class 'Post' not found

So it seems the morphTo() function needs the full namespace in the database.

Am I missing something here? We have the ability to declare a $morphClass, so we don't need the full namespace in the database and it works for one side of the relationship, but then it doesn't work for the reverse relationship ? Seems like it really should.

Last updated 2 years ago.
0

I've run into this same issue. Have you found a solution?

0

Same issue here too.

0

Have you tried passing the relationship name to morphTo?

public function commentable()
{
    return $this->morphTo('commentable');
}
0

Sign in to participate in this thread!

Eventy

Your banner here too?

DeanStr deanstr Joined 6 Aug 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.