belongsTo and hasOne relation in laravel

Submitted by sanjok1988 - 5 months ago

The main difference is which side of the relationship holds the relationship's foreign key. The model that calls $this->belongsTo() is the owned model in one-to-one and many-to-one relationships and holds the key to the owning model.

//Example one-to-one relationship:

class User extends Model {
  public function car() {
    // user has at maximum one car, 
    // so $user->car will return a single model
    return $this->hasOne('Car');
  }
}

class Car extends Model {
  public function owner() {
    // cars table has owner_id field that stores id of related user model
    return $this->belongsTo('User'); 
  }
}

//Example one-to-many relationship:

class User extends Model {
  public function phoneNumbers() {
    // user can have multiple phone numbers, 
    // so $user->phoneNumbers will return a collection of models
    return $this->hasMany('PhoneNumber');
  }
}

class PhoneNumber extends Model {
  public function owner() {
    // phone_numbers table has owner_id field that stores id of related user model
    return $this->belongsTo('User'); 
  }
}