belongsToMany(Course::class, 'sections'); } public function sections() { return $this->hasMany(Section::class); } public function professors() { return $this->belongsToMany(Professor::class)->withPivot('admin_load', 'investigative_load'); } public function getIsFutureAttribute() { return Semester::orderBy('code', 'desc')->take(6)->get()->contains('code', $this->code); } /** * Returns a clone of this semester with the provided code and alpha. * This functions also copies every section and professor_section * * @param string $newSemCode * @param string $newSemAlpha * @param int $dept_id * * @return Semester */ public function clone(string $newSemCode, string $newSemAlpha, int $dept_id) { // if (Semester::find($newSemCode)) { // throw new Exception('A semester with code ' . $newSemCode . ' already exists'); // } $semClone = Semester::firstOrCreate( ['code' => $newSemCode], ['alpha' => $newSemAlpha], ); $this->loadMissing([ 'sections' => function ($query) use ($dept_id) { $query->select('sections.id', 'course_id', 'semester_code', 'sections.code', 'student_count', 'sections.syllabus', 'credits', 'quota') ->join('courses', 'courses.id', '=', 'sections.course_id') ->where('dept_id', '=', $dept_id); }, 'sections.professors', 'sections.schedules' ]); // Copy all sections to new semester foreach($this->sections as $section) { $sectionClone = $section->replicate(); $sectionClone->semester_code = $semClone->code; $existingSection = Section::where([['semester_code', '=', $sectionClone->semester_code], ['course_id', '=', $sectionClone->course_id], ['code', '=' , $sectionClone->code]])->first(); if (!$existingSection) { $sectionClone->save(); foreach($section->professors as $professor) { $sectionClone->professors()->attach($professor, ['percent' => $professor->pivot->percent]); } foreach($section->schedules as $schedule) { $scheduleClone = $schedule->replicate(); $scheduleClone->section_id = $sectionClone->id; $scheduleClone->save(); $sectionClone->schedules()->save($scheduleClone); } } } return $semClone; } }