Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

seen's avatar
Level 4

Difference between `hasOne` and `belongsTo`

What is the difference between hasOne and belongsTo relationships in Laravel Eloquent?

0 likes
2 replies
muathye's avatar
muathye
Best Answer
Level 41

In Laravel Eloquent, hasOne and belongsTo are used to define one-to-one relationships between models.

1. hasOne Relationship:

  • Used in the parent model to define that it has one related child model.
  • The foreign key is stored in the child model.
  • Example: A User has one Profile.
class User extends Model
{
    public function profile()
    {
        return $this->hasOne(Profile::class);
    }
}

2. belongsTo Relationship:

  • Used in the child model to define that it belongs to a parent model.
  • The foreign key is stored in the same model where belongsTo is defined.
  • Example: A Profile belongs to a User.
class Profile extends Model
{
    public function user()
    {
        return $this->belongsTo(User::class);
    }
}

Key Differences:

Feature hasOne belongsTo
Defined in Parent Model Child Model
Foreign Key In child table In child table
Example User has one Profile Profile belongs to User

'I used chatgpt to answer, and it is correct answer'

3 likes
seen's avatar
Level 4

@muathye Thank you, I know chatgpt can answer me too 😉, but I wanted to ensure the correct answered from real developer.

1 like

Please or to participate in this conversation.