I have two eloquent models: User, Project with a many-to-many relationship between them.
In User model:
public function projects()
{
return $this->belongsToMany(Project::class)->withTimestamps();
}
and in Project model:
public function users()
{
return $this->belongsToMany(User::class)->withTimestamps();
}
The database tables are user, project and the pivot table is project_user. The table fields are as follows: user: [id, name], project: [id, data], project_user: [user_id, project_id].
I need to implement a query that given a user returns all the users that are participating in all his projects and I cannot figure out how to do this with eloquent.
Actually the tables that are needed in that query are user and project_user.
I guess a possible sql query could be something like this:
SELECT id, name FROM user WHERE id IN (SELECT user_id FROM project_user WHERE project_id IN (SELECT project_id FROM project_user WHERE user_id = 8))
In Eloquent I do not even know how to approach this. I am new to it. For instance do I somehow need the whole relationship so as to use wherePivot() or try subqueries in where() clauses in the User model? Any help or hints would be much appreciated.