What is the difference between hasOne and hasMany in Eloquent, and when should you use each?
hasOne defines a one-to-one relationship. A model owns exactly one related record:
// A User has one Profile
class User extends Model
{
public function profile(): HasOne
{
return $this->hasOne(Profile::class);
}
}
$profile = User::find(1)->profile; // single Profile model
hasMany defines a one-to-many relationship. A model owns multiple related records:
// A User has many Posts
class User extends Model
{
public function posts(): HasMany
{
return $this->hasMany(Post::class);
}
}
$posts = User::find(1)->posts; // Collection of Post models
| hasOne | hasMany | |
|---|---|---|
| Returns | Single model or null | Collection (possibly empty) |
| DB constraint | Unique foreign key | Non-unique foreign key |
| Example | User → Profile | User → Posts |
$users = User::with(['profile', 'posts'])->get();
All Comments