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

Sinnbeck's avatar
Level 102

whereHas using muliple tables (or perhaps join)

Hi I have 3 tables. users, pages and user_groups Each user is part of a user group and on the table is a max_pages column. Now I need to get all users that still have not exceeded their max_pages count.

Is there an eloquent way of doing this or do I need to use the query builder. I was hoping that I somehow could use whereHas but I cannot get it to work at all, sadly.

I am using mssql and laravel 5.7

0 likes
4 replies
Vilfago's avatar

I think you will go for a query builder with some join and raw sql here...

Vilfago's avatar

If you don't have so many groups, you can maybe try something like that.

Add a column page_count on users table, and do something like

$groups = Group::all();

foreach($groups as $group){
  $group->load('users' => function($q) use ($group){
    $q->where('page_count', '<', $group->max_pages); });
}
Sinnbeck's avatar
Level 102

It is a great idea. Sadly it is a database used by another system (not created in-house), and I cannot edit it in any way. I got it working using some some join and raw.

Please or to participate in this conversation.