laravel relationships

Difference between polymorphic and Standard relationship in Laravel

In Laravel, Eloquent relationships provide a convenient way to interact with related database tables. Both polymorphic relationships and standard (non-polymorphic) relationships fall under the umbrella of Eloquent relationships, but they serve different purposes.

Standard (Non-Polymorphic) Relationships:

  • In standard relationships, you have a straightforward connection between two models using foreign key constraints.
  • For example, you might have a Post model and a Comment model, where each comment belongs to a post. In this case, you would have a posts table and a comments table. The comments table would have a foreign key column like post_id that references the id column in the posts table.
  • You define the relationship in the models, and Eloquent provides methods to query and retrieve related data.

Post Model:

// Post Model
class Post extends Model
{
    public function comments()
    {
        return $this->hasMany(Comment::class);
    }
}

Comment Model:

// Comment Model
class Comment extends Model
{
    public function post()
    {
        return $this->belongsTo(Post::class);
    }
}

Usage:

// Get comments for a post
$comments = Post::find(1)->comments;

Polymorphic Relationships:

  • Polymorphic relationships allow a model to belong to more than one type of other model on a single association.
  • This is useful when you have entities that can be associated with multiple types of other entities without having to create a separate table for each relationship.
  • In a polymorphic relationship, the related model’s type and ID are stored in columns on the calling model’s table.
  • For example, you might have a Comment model that can belong to both Post and Video models. In this case, you would have a comments table with commentable_type and commentable_id columns.

Comment Model:

// Comment Model
class Comment extends Model
{
    public function commentable()
    {
        return $this->morphTo();
    }
}

Post Model:

// Post Model
class Post extends Model
{
    public function comments()
    {
        return $this->morphMany(Comment::class, 'commentable');
    }
}

Video Model:

// Video Model
class Video extends Model
{
    public function comments()
    {
        return $this->morphMany(Comment::class, 'commentable');
    }
}

Usage:

// Get comments for a post
$comments = Post::find(1)->comments;

// Get comments for a video
$comments = Video::find(1)->comments;

In summary, standard relationships are used when there’s a direct one-to-many or many-to-one connection between models, while polymorphic relationships are used when a model can belong to multiple types of other models on a single association.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top