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 $with 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?
To filter the CustomerRewards collection loaded via the $with method, you can use Laravel's collection methods such as filter() or where(). However, since you are applying the filter and the eger Loaded relation has not yet been loaded, you must use the whereHas() method as well as the () method to load only the appropriate customer rewards. Here's how you can change your code:
$companies = Company::with(['customerRewards' => function($query) use ($customer) {
$query->where('customer_id', $customer->id);
}])
->has('customerRewards')
->whereHas('customerRewards', function($query) use ($customer) {
$query->where('customer_id', $customer->id);
})
->get();
hope this will work for you