🔴 Laravel
Advanced
What is the difference between belongsToMany and hasMany in Eloquent?
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.