Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

185
Views
relationships with multiple pivot table Eloquent/Laravel

I have 4 table

users
 id
 name

school
 id
 name

user_school
 id
 user_id
 school_id

user_role
 id
 user_role
 role_id

We need to find school users list whose have role id is 2

we use belongsToMany but not success

public function totalAdmin(){
        return $this->belongsToMany('App\Models\User','user_school', 'school_id','user_id')->where('user_school.status',1)->where('user_school.deleted',0);
    }
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Assuming you have relationships:

  • User-Role named roles (with pivot user_role)
  • School-User named users (with pivot user_school)

You can do:

School::users()->whereHas('roles', function ($q) {
   $q->where('id', 2);
});

You can probably transfer it in the relationship as well:

public function totalAdmin(){
    return $this->belongsToMany('App\Models\User','user_school','school_id','user_id')
      ->whereHas('roles', function($q) { $q->where('id', 2); });
}
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!