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

jrichmo93's avatar

Query by count of relationship comparison to parent field value

I'm building a project management tool and need to query for all projects that aren't full. The amount of users in a project is specified when the project is created. So essentially I need a query like below:

Project::has('users', '<', 'project.user_count')

Looking at the bindings from the query, project.user_count evaluates to 0. Is there anyway to accomplish this? Any help is appreciated.

0 likes
1 reply
Talinon's avatar

You should be able to do something like this:


Project::has('users')->with('users')->get()->filter(function ($project) {

    $project_count = $project->users->count();

    return $project->user_count < $project_count;

});

Please or to participate in this conversation.