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 with withPivot, timestamps with withTimestamps, a custom pivot model with using().
  • hasManyThrough: reach distant records through an intermediate model (a country's posts through users).
  • Polymorphic (morphTo / morphMany): one table serves several parents using commentable_type and commentable_id, for example comments on posts and videos. Many-to-many polymorphic uses morphToMany (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

← All Laravel questions