Home > Mobile >  laravel belongstomany query
laravel belongstomany query

Time:06-17

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

CodePudding user response:

The constraint should be specified within the whereHas

Since school relationship on User model is a belongsToMany it will return a collection. So will need to pluck the id from the collection and use whereIn constraint, like below

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

CodePudding user response:

Solved with

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