What is the difference between belongsToMany and hasMany in Eloquent?
Why Interviewers Ask This
Interviewers ask this to evaluate whether you have the depth of knowledge needed to mentor others and lead technical decisions. The expected answer goes beyond definitions into practical implications and real-world consequences.
Answer
hasMany represents a one-to-many relationship: one Post has many Comments. The foreign key (post_id) lives in the comments table. Direct relationship — no intermediate table. belongsToMany represents a many-to-many relationship: a User has many Roles, and a Role has many Users. Requires a pivot table (role_user) containing both foreign keys. Define on both models: User::roles() returns $this->belongsToMany(Role::class). Attach: $user->roles()->attach($roleId). Detach: detach(). Sync (replace all): sync([$roleId1, $roleId2]). Access pivot data: $user->roles()->first()->pivot->created_at. Store extra pivot columns: ->withPivot("level")->withTimestamps(). Create a custom Pivot model with ->using(UserRole::class) for custom pivot logic.
Pro Tip
This topic has Laravel-specific nuances that differ from general programming. Highlighting those nuances in your answer shows expertise rather than generic knowledge.