What is the difference between hasOne and hasMany in Laravel?

What is the difference between hasOne and hasMany in Laravel?

What is the difference between hasOne and hasMany in Laravel?

Question

What is the difference between hasOne and hasMany in Eloquent, and when should you use each?

Answer

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

Key Differences

hasOnehasMany
ReturnsSingle model or nullCollection (possibly empty)
DB constraintUnique foreign keyNon-unique foreign key
ExampleUser → ProfileUser → Posts

Eager Loading (avoid N+1)

$users = User::with(['profile', 'posts'])->get();
All Comments