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
belongsTois 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