Use wherePivot to constrain the query based on a pivot table column.
The $category variable is not in scope for the Closure
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
Assuming both models ItemsList and Items are set correctly with belongsToMany , and the pivot table is items_to_list, I need to get the list of items with selected category and where the items are banned in the pivot table
Does this query seem to be correct
$lists = ItemsList::whereIn('id', $array_of_ids)
->with('items')
->withCount(['items' => function ($query) {
$query->where('items.category', $category)
->where('items_to_list.banned', 1);
}])->get();
@cooperino I was responding on my phone earlier and didn't notice that the banned constraint was inside the withCount Closure. In that case, I expect the original implementation was ok - the necessary join should be handled by Eloquent. This should be correct:
$lists = ItemsList::whereIn('id', $array_of_ids)
->with('items')
->withCount(['items' => function ($query) {
$query->where('items.category', $category)
->where('items_to_list .banned', 1);
}])->get();
Please or to participate in this conversation.