I have this piece of code that filters only companies that have some customerRewards
related to and belonging to some customer. The whereHas()
filter works fine, but the result of customerRewards from $ also contains items with different customer IDs.
$companies = Company::with(['customerRewards']) // This is the problem
->has('customerRewards')
->whereHas('customerRewards', function(Builder $q) use ($customer) {
$q->where('customer_id', $customer->id); // This works as expected
})
->get();
How can I filter the $with collection?
2
Answers
In Laravel 9.x and above, you can use withWhereHas() to eager load the
customerRewards
relationship for the companies that have rewards for the specific customer.