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

Egyptian's avatar

Selecting rows where a column equals the result of count "withCount"

Dear all I have 2 tables Users & Tasks

users table

| id | name | requiredtasks | | ------------- | ------------- | ------------- | | 1 | Mostafa | 5 | | 2 | Ahmed | 4 |

tasks table

| id | task | user_id | status | | 1 | task a | 1 | approved | | 2 | task b | 1 | canceled | | 3 | task c | 2 | approved |

I want to select the users whose have approved tasks less than the number in their "requiredtasks" columns

$users = User::withCount([
    'tasks' => function ($query) {
        $query->where('status', 'approved');
        }
    ])
    ->where('requiredtasks', '>', 'tasks_count') // How can I do this line
    ->get();

Thanks a lot

0 likes
2 replies

Please or to participate in this conversation.