Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

raphyabak's avatar

Laravel Belongstomany Eloquent query

I have two models, User and School; they both return belongs to many of each of them. I'm trying to return a list of Users that has the same School as the user logged in.

USER MODEL

 public function school(){

        return $this->belongsToMany(School::class, 'school_user');
    }
SCHOOL MODEL

public function user(){

      return $this->belongsToMany(User::class, 'school_user');
    }
The Eloquent Query

$students = User::role('Student')->with('school')->where('school_id', auth()->user()->school->id)->latest()->paginate(25);

But it's not working. kindly help out. Thank you

0 likes
2 replies
undeportedmexican's avatar

Can you confirm what you get when you do auth()->user()->school->id?

Because, unless I'm missing something, auth()->user()->school should return a collection of schools, not only one.

If that's the case, you would need to do something like auth()->user()->school->first()->id.

Am I understanding something wrong?

raphyabak's avatar
raphyabak
OP
Best Answer
Level 1

Got it working with

$students = User::role('Student')->whereHas('school', function($query) {
            $query->whereIn('school_id', auth()->user()->school->pluck('id'));
        })
        ->latest()
        ->paginate(25);

Please or to participate in this conversation.