Eloquent Relationships
hasOne, hasMany, belongsTo, and many-to-many
Eloquent relationships define how models connect to each other through foreign keys.
A User has one Profile. One-to-one relationship.
users
| id | name |
|---|---|
| 1 | Alice |
profiles
| id | user_id | bio |
|---|---|---|
| 1 | 1 | Developer |
hasOne
PHP
// User model
public function profile() {
return $this->hasOne(Profile::class);
}
$user->profile->bio; // 'Developer'