teacherClass ->newQuery() ->with([ 'teacher:id,firstname,lastname', ]) ->when(filled($schoolYear), fn ($q) => $q->where('school_year', $schoolYear)) ->get() ->map(function ($row) { $row->teacher_full_name = trim( ((string) optional($row->teacher)->firstname) . ' ' . ((string) optional($row->teacher)->lastname) ); return $row; }); } public function loadStudentClasses(?string $schoolYear = null): Collection { return $this->studentClass ->newQuery() ->with([ 'student:id,firstname,lastname,age,gender,registration_grade,photo_consent,tuition_paid,school_id,is_active', ]) ->whereHas('student', fn ($q) => $q->where('is_active', 1)) ->when(filled($schoolYear), fn ($q) => $q->where('school_year', $schoolYear)) ->get(); } }