I think that relationship which you need is has many through
https://laravel.com/docs/5.3/eloquent-relationships#has-many-through
Here is example
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
How to set a hasMany relation between 3 tables? Imagine the example:
I have users, teams, roles and finally to connect all, user_teams.
A user could belong to multiple teams, and have a different role in each team. My user_teams table is represented like this:
user_id integer
team_id integer
role_id integer
And this is my 3 models so far:
class User extends Eloquent
{
public $timestamps = false;
protected $table = 'users';
protected $fillable = ['name', 'email', 'password', 'locale', 'token', 'status', 'created', 'updated'];
public function teams()
{
return $this->belongsToMany('Models\Team', 'user_teams', 'user_id', 'team_id');
}
}
class Team extends Eloquent
{
public $timestamps = false;
protected $table = 'teams';
protected $fillable = ['name', 'slug', 'type', 'created', 'updated'];
public function users()
{
return $this->belongsToMany('Models\User', 'user_teams', 'team_id', 'user_id');
}
}
class Team extends Eloquent
{
public $timestamps = false;
protected $table = 'teams';
protected $fillable = ['name', 'slug', 'type', 'created', 'updated'];
public function users()
{
return $this->belongsToMany('Models\User', 'teams_users', 'team_id', 'user_id');
}
}
Any ideas on how to achieve this?
Please or to participate in this conversation.