Laravel Polymorphic RelationShip (part1).

Aman jain
4 min readJun 24, 2023

What is Laravel Polymorphic Relationship?

Laravel Polymorphic Relationship is a feature that allows you to establish associations between different model types using a single association. In simpler terms, it enables a model to belong to multiple other models on a single association. This powerful concept eliminates the need for complex and redundant database structures, providing a more efficient and flexible way to handle relationships.

How Does Polymorphic Relationship Work?

Polymorphic relationships in Laravel are built on three key components: the polymorphic model, the polymorphic type, and the polymorphic ID.. The polymorphic model represents the model that can belong to multiple other models, while the polymorphic type and ID determine the specific relationship.

Let’s look at an example where a blog post can receive comments from both users and administrators to demonstrate this. To address both instances, we can utilise a single comments table with a polymorphic connection rather than making separate tables for user comments and admin comments. In the comments table, there would be columns for commentable_id, commentable_type, and content. Commentable_id would indicate the associated model’s ID, while commentable_type would indicate the type of model.

--

--

Aman jain

I’m a developer who shares advanced Laravel and Node.js insights on Medium.