Eloquent with whereHas in laravel

Submitted by sanjok1988 - 3 years ago

Here a user has a location with many to many positions. This query finds users having position id 4 and location id 6. the tables are users, profile, locations. and profile has location_id.

User::whereHas('positions', function ($q) {
        $q->wherePositionId(4);
    })->whereHas('profile', function ($q) {
        $q->whereLocationId(6);
    })->with(['profile', 'positions'=>function ($q) {
        $q->wherePositionId(4);
    }])->get();
    
    
//in user model
public function profile()
    {
        return $this->hasOne(Profile::class, 'user_id', 'id');
    }

public function positions()
{
    return $this->belongsToMany(\App\Positions::class, 'user_positions', 'user_id', 'position_id')
    ->withPivot(['position_id', 'user_id']); //if you don't need pivot you can remove it
}