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.
Have you tried passing the relationship name to morphTo
?
public function commentable()
{
return $this->morphTo('commentable');
}
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community