skip to Main Content

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


  1. 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.

    $companies = Company::withWhereHas('customerRewards', function ($query) use ($customer) {
        $query->where('customer_id', $customer->id);
    })->get();
    
    Login or Signup to reply.
  2. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search