Posted on under Laravel by Owen Conti.
By default, a
whereHas
query checks to see that the given relation has at least one row for the given constraint, ie:
1$authorIds = [1, 2];2 3Post::whereHas('authors', function ($query, $authorIds) {4 $query->whereIn('id', $authorIds);5})->get();
The above query will return posts that were authored by authors with ID 1 or 2. If, however, we want to find the posts that were authored by both authors 1 and 2, we need to change the query to tell Laravel to include posts that return 2 author relation rows when filtered:
1 2$authorIds = [1, 2];3 4Post::whereHas('authors', function ($query, $authorIds) {5 $query->whereIn('id', $authorIds);6}, '=', count($authorIds))->get();
The above query tells Laravel to load the posts that have 2 author relation records when the author relation records are filtered by the given array of IDs.
Hopefully you found this article useful! If you did, share it on X!
Found an issue with the article? Submit your edits against the repository.