join('customer_jobs', 'customer_jobs.id', '=', 'tasks.customer_job_id') ->where('tasks.planned_from', '>=', CarbonImmutable::parse($after)->addDay()->toDateString()) ->where('tasks.planned_from', '<', CarbonImmutable::parse($to)->addDay()->toDateString()) ->where('tasks.status', '!=', TaskStatus::Done->value) ->where('customer_jobs.status', '!=', JobStatus::Archived->value) ->orderBy('tasks.planned_from') ->orderBy('tasks.id') ->get(['tasks.id', 'tasks.title', 'tasks.planned_from', 'tasks.assignee_user_id', 'customer_jobs.id as job_id', 'customer_jobs.number', 'customer_jobs.name']); $members = DB::table('task_members') ->whereIn('task_id', $rows->pluck('id')->all()) ->get(['task_id', 'user_id']) ->groupBy('task_id'); return $rows->map(function (object $row) use ($members): UpcomingTask { $recipients = ($members->get($row->id) ?? collect())->pluck('user_id'); if ($row->assignee_user_id !== null) { $recipients->prepend($row->assignee_user_id); } return new UpcomingTask( (int) $row->id, (string) $row->title, (int) $row->job_id, (string) $row->number, (string) $row->name, substr((string) $row->planned_from, 0, 10), $recipients->map(fn ($id): int => (int) $id)->unique()->values()->all(), ); })->values()->all(); } }