Polymorphic relationships in Laravel

                    It is a common scenario in software development to have models that belong to more that just one entity. This type of models are connected to other models but will maintain its structure. In general polymorphism can be defined as the ability to appear in many forms. There are four types of polymorphic relationships and they are one to one, one to many, many to many and custom polymorphic types.

For example consider a blog users can comment on a page or a post but the basic structure will be the same. We have two entities in this example Post and Page.

For this we need to create two different comment tables i.e. posts_comments and pages_comments and both of them do the same thing. Database can be set up as given below.

posts:

  id

  title

  content

 

pages:

  id

  body

 

comments:

  id

  commentable_id

  commentable_type

  date

We have totally three entities i.e. Post, Page, Comments. Post can have comments, Page can have comments and comments belong to either of the two entities. Create migrations for each tables. Now create models for Post, Page and Comments. In the models we have to use morphmany() and morphTo() methods which helps us to define polymorphic relationship. Page and Post models use the morphMany() method to comment model. You can use dynamic properties in the model to get comments. In page
// getting comments for a sample post...
  $post = Post::find(13);

  foreach($post->comment as $comment)
  {
    // working with comment here...
  }
In Post
// getting comments for a sample post...
  $post = Post::find(13);

  foreach($post->comment as $comment)
  {
    // working with comment here...
  }
To find out which entity the comment belongs to reverse the above.
$comment = Comment::find(23);

  // getting the model...
  var_dump($comment->commentable);
You can add other model to use the relationship Comment without breaking the code.