Laravel Eloquent Many-to-Many query whereIn Laravel Eloquent Many-to-Many query whereIn laravel laravel

Laravel Eloquent Many-to-Many query whereIn


Use the whereHas() method:

$dogs = Dog::whereHas('owners', function($q) use($ownerIds) {    $q->whereIn('id', $ownerIds);})->get();


Try

$associateDogs = Dog::with(['owners' => function($query) use ($listOfOwners) {    $query->whereIn('id', $listOfOwners);}])->get();


I tried the two suggested solutions but I was getting an error that said that id was not unique.I solved like this:

$dogs = Dog::whereHas('owners', function($q) use($ownerIds) {    $q->whereIn('owner_id', $ownerIds);})->get();