Laravel HasMany Relation On Multiple Columns

I'm trying to setup Laravel relations on an already existing database which I'm unable to change.

In this database there is a table named Teams with columns:

  • Teamleader_1
  • Teamleader_2

Furthermore there's a table named Users with a column:

  • User_id

The relation between these tables is as follows: Users.User_id = Teams.Teamleader_1 OR Users.User_id = Teams.Teamleader 2

How can I setup a hasMany relationship between Users and Teams on both teamleader columns?



First, you need to define 2 relations in your team model:

public function teamleader1() {
  return $this->belongsTo(User::class, 'Teamleader_1', 'User_id');

public function teamleader2() {
  return $this->belongsTo(User::class, 'Teamleader_2', 'User_id');

Once you have it, define an accessor that will get the teamleader from either of those relations:

public function getTeamleaderAttribute() {
  return $this->teamleader1 ?: $this->teamleader2;

Once you have it, you should be able to access the user by calling:

$teamLeader = $team->teamleader;