is there a way to optimize this query?
Applicant::query()->with('interviews', 'interviews.jobListing', 'latestEducationHistory')
->when($search, function ($q) use ($search) {
$q->whereAny($fields, 'LIKE', "%{$search}%");
})->when($status, fn ($q) => $q->where('status', $status))
->when(! $onlyRejected, fn ($q) => $q->where('status', '!=', ApplicantStatus::Rejected))
->when($onlyRejected, fn ($q) => $q->where('status', '=', ApplicantStatus::Rejected))
->when($startYearBorn, fn ($query) => $query->whereYear('date_of_birth', '>=', $startYearBorn))
->when($endYearBorn, fn ($query) => $query->whereYear('date_of_birth', '<=', $endYearBorn))
->when($cityId, fn ($q) => $q->where('city_id', $cityId))
->when($positionAppliedId, fn ($query) => $query->whereRelation('interviews', 'job_listing_id', '=', $positionAppliedId))
->when($startDate, fn ($query) => $query->whereRelation('interviews', 'created_at', '>=', $startDate))
->when($endDate, fn ($query) => $query->whereRelation('interviews', 'created_at', '<=', $endDate))
->when($statuses, fn ($q) => $q->whereIn('status', $statuses))
->where('status', '!=', ApplicantStatus::ConvertedToEmployee)
->select('applicants.*')
->leftJoin('applicant_education_histories as latest_education', function ($join) {
$join->on('applicants.id', '=', 'latest_education.applicant_id')
->whereRaw('latest_education.graduate_year = (SELECT MAX(graduate_year) FROM applicant_education_histories WHERE applicant_id = applicants.id)');
})
->orderBy('latest_education.gpa', $sortGpa == 'desc' ? 'desc' : 'asc')