Recall & Review
beginner
What is a polymorphic relationship in Laravel?
A polymorphic relationship allows a model to belong to more than one other model on a single association. For example, a Comment model can belong to both a Post and a Video model using the same relationship.
Click to reveal answer
intermediate
How do you define a polymorphic one-to-many relationship in Laravel?
Use the
morphMany method on the parent model and morphTo on the child model. For example, a Post model has many comments with comments() using morphMany, and Comment uses commentable() with morphTo.Click to reveal answer
beginner
What database columns are required for polymorphic relationships?
You need two columns on the related table: <code>{relation}_id</code> and <code>{relation}_type</code>. For example, in comments table, <code>commentable_id</code> stores the ID and <code>commentable_type</code> stores the model class name like 'App\\Models\\Post'.Click to reveal answer
advanced
Can polymorphic relationships be used with many-to-many relationships in Laravel?
Yes, Laravel supports polymorphic many-to-many relationships using
morphToMany and morphedByMany methods. This allows a model to belong to multiple models on a many-to-many basis with a single pivot table.Click to reveal answer
intermediate
Why use polymorphic relationships instead of multiple foreign keys?
Polymorphic relationships simplify the database design by using one set of columns to relate to multiple models. This avoids adding many nullable foreign keys and makes the code cleaner and easier to maintain.
Click to reveal answer
Which two columns are essential for a polymorphic relationship in Laravel?
✗ Incorrect
The columns must be named {relation}_id and {relation}_type, for example commentable_id and commentable_type.
Which method defines the inverse side of a polymorphic one-to-many relationship in Laravel?
✗ Incorrect
morphTo is used on the child model to define the inverse polymorphic relationship.What does the
morphMany method do in Laravel?✗ Incorrect
morphMany defines a polymorphic one-to-many relationship from the parent model.Which Laravel method is used for polymorphic many-to-many relationships?
✗ Incorrect
morphToMany is used to define polymorphic many-to-many relationships.Why might you choose polymorphic relationships in your Laravel app?
✗ Incorrect
Polymorphic relationships reduce complexity by using one relation for multiple models, avoiding many nullable foreign keys.
Explain how to set up a polymorphic one-to-many relationship in Laravel with an example.
Think about how comments can belong to posts or videos using the same table.
You got /4 concepts.
Describe the benefits of using polymorphic relationships over multiple foreign keys in Laravel.
Consider how many models can share the same related data type.
You got /4 concepts.