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

Aktheon's avatar

Eloquent complex relationship with filter

Hello. I've read documentation few times and can't figure out the following problem.

I have 3 tables: 'accesses' table with columns: id, product_user_id

'product_user' table: id (this one is used by accesses) user_id product_id

'product' table: id (used by product_user)

I wanna use relations for Elaquent models. I need to get all accesses for products for specific user_id.

I do know i can use belongsToMany or hasOneThrough to query accesses related to specific product. But how can i filter this by user_id?

The second problem is i have 3rows for specific user_id in product_user table. Can i do something like ProductUser::where('user_id',7)->product->accesses->get() Or can i do Product::all()->accesses and then somehow apply filter by user_id?

0 likes
3 replies
Snapey's avatar
Snapey
Best Answer
Level 122

so its a simple belongsToMany from either side of a pivot table?

You can use the whereHas() method to mention the user that you are interested in.

eg

Product::whereHas('accesses', function($query) use ($user){
    $query->where('user_id', $user->id);
})->with('accesses.user')->get();

I'm guessing here at relationship names so you will have to adapt to suit.

Aktheon's avatar

somehow it works and returns proper results.

$prod_w_accesses = Product::whereHas('accesses', function($query){ $query->where('user_id', 5); })->with('accesses')->get();

thanks for this sort of magic

Snapey's avatar

If you install Laravel Debugbar, amongst other useful features it will show you the queries being executed.

Please or to participate in this conversation.