Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

beertastic's avatar

hasManyThrough, filter on PARENT table.

3 tables:

  1. Store (has field user_id)
  2. Product (has ref store_id)
  3. Order (has ref product_id)

I am on Store model. I want to list all orders that belong to a store.user_id (as there are 1000s of stores, but owned by a few people)

Here's a model call:

public function receivedOrders($user_id = null)
{
    $orders = $this->hasManyThrough(Order::class, Product::class);
    if ($user_id != null) {
        $orders->where('user_id', $user_id);
    }
    return $orders;
}

The Store table (where I want to filter by user_id) is not referenced in this call at all.

Any idea how to filter all orders, based on all Stores, that are owned by a single user.

I love learning eloquent, but wonder if I should just use:

https://laravel.com/docs/7.x/queries

0 likes
1 reply
beertastic's avatar
beertastic
OP
Best Answer
Level 2

I'm a tool.. I just had to add a filter when calling the master list.

So in my controller I've got:

$stores = Store::where('user_id', Auth::user()->id)->get();

The rest of the Model magic will then only return that user results.

So simple, I'm getting more coffee. urgh

Please or to participate in this conversation.