Laravel interview question · Most asked
Explain Eloquent relationship types, including polymorphic relationships.
Summary
One-to-one (hasOne/belongsTo), one-to-many (hasMany/belongsTo), many-to-many (belongsToMany with a pivot table), has-one/has-many-through, and polymorphic relationships where a model can belong to more than one other model type.
Longer Answer
hasMany/belongsTo: the foreign key lives on the child (posts.user_id).belongsToMany: a pivot table (role_user); extra pivot columns withwithPivot, timestamps withwithTimestamps, a custom pivot model withusing().hasManyThrough: reach distant records through an intermediate model (a country's posts through users).- Polymorphic (
morphTo/morphMany): one table serves several parents usingcommentable_typeandcommentable_id, for example comments on posts and videos. Many-to-many polymorphic usesmorphToMany(tags).
Polymorphic relations cannot have real foreign-key constraints, so the database cannot enforce integrity. Use a morph map (Relation::enforceMorphMap) so class names are not stored in the database and refactors do not break data.
Key Points
- Know where the foreign key lives for each type.
- Pivot tables for many-to-many, with extra columns.
- Polymorphic:
*_type+*_id, no FK constraints. - Use an enforced morph map.
Explanation
Follow-up questions
- What are the trade-offs of polymorphic relations versus separate tables?
More most-asked Laravel questions
- How do you validate requests in Laravel? Why use Form Requests?
- Gates or policies: how does authorization work in Laravel?
- What is mass assignment, and how do $fillable and $guarded protect against it?
- How do database transactions work in Laravel, and what pitfalls should you know?
- Which Artisan commands would you run when deploying Laravel to production, and why?
- What is the service container, and how does dependency injection work in Laravel?
- What is the N+1 query problem in Eloquent and how do you prevent it?
- How do queues work in Laravel?