What is the difference between hasOne/hasMany and belongsTo/belongsToMany relation?

Andrew

Administrator
Staff member
Messages
27
Likes
6
Trophy Points
5
Followers
2
Joined
Mar 17, 2022
The only difference between hasOne/hasMany and belongsTo/belongsToMany is where the foreign key column is located.
  • hasOne and hasMany - you are telling Laravel that this table does not have the foreign key.
  • belongsTo and belongsToMany - you are telling Laravel that this table holds the foreign key that connects it to the other table.

Example:
PHP:
# User.php (Model)
public function address (): HasOne
{
    return $this->hasOne(UserAddress::class); // This table does not have the foreign key
}

# UserAddress.php (Model)
public function user(): BelongsTo
{
    return $this->belongsTo(User::class, 'user_id', 'id'); // This table has the foreign key (user_id)
}
 
Top