Eloquent with whereHas in laravel

Submitted by sanjok1988 - 3 months 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) {
    })->whereHas('profile', function ($q) {
    })->with(['profile', 'positions'=>function ($q) {
//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