Basic Implementation
To illustrate this with a practical example, suppose you have two entities, Post and Video, both capable of receiving comments. First, you need to define the model Comment, including the fields commentable_id and commentable_type.
public function commentable() { return $this->morphTo(); }Thus, your class Comment can be associated with any model that implements the corresponding inverse relationship.
We create the necessary migrations
Next, the migrations for the respective tables are created:
Schema::create(comments, function (Blueprint $table) { $table->increments(id); $table->text(body); $table->morphs(commentable); $table->timestamps(); });Let\'s analyze the concept of inheritance: With this configuration we achieve to reduce redundancy in the project structure through the use of abstraction. Comparatively, if we limited ourselves to simple one-to-many or many-to-many relationships, we would need more effort to keep multiple models synchronized and consistent.
Differences with other relationships
| Relationship | Use Case |
|---|---|
| One-to-One | A user has a unique profile. |
| One-to-Many | A post has many Comments. |
| Polymorphic | Multiple content types can have many comments. |
Note how the polymorphic relationship can encompass cases where one-to-one or one-to-many would be insufficient or unnecessarily increase code complexity.
More on programming and web development here.
Comments
0Be the first to comment