0👍
Have you created a Task Model? It looks like you have already done that for Department. If you create a task model (https://laravel.com/docs/8.x/eloquent), you can create a one-to-many relationship between Task and Department and use a count method something like this:
$departments = Department::where('x', 'x')->withCount(['tasks as completed_tasks' => function(Builder $query){
$query->whereNotNull('completed_at');
}])->get();
Then it will come back in your $departments collection as a completed_tasks attribute.
It looks like you might also benefit from creating a relationship between User and Task so you dont have to have a ->join(‘users’, ‘users.id’, ‘=’ , ‘tasks.user_id’) in your query.
Source:stackexchange.com