Laravel defining a many-to-many relationship with the same table
Thanks to @d3jn's comment on my question I was able to solve my problem. So I am posting the solution here just in case someone else might need it.
I am relating the Post
model to itself not to the pivot model RelatedPost
. So I don't need a RelatedPost
model. I only need a pivot table (related_post
), and the relation's id
s namely related_id
and post_id
.
So with my migration unchanged, I only need to do away with the RelatedPost
model and change my related()
method in the Post
model to look like this:
public function related(){ return $this->belongsToMany(Post::class, 'related_posts', 'post_id', 'related_id');}
And now everything works.