/** * Update the specified resource in storage. * * @param int $id * @return Response */ public function update(MonthlyReportRequest $request, $id) { //Find report $report = MonthlyReport::find($id); //Getting all the information of the form, expect the user id, //due to keep the report related with its creator $report->fill($request->except('user_id')); $report->save(); //If the student is absent, it is not necessary create the sessions if ($report->student_present == true) { //##Updating the old sessions $sessionsIds = array(); foreach ($request->input('old', array()) as $id => $sessionData) { $session = Session::find($id) ?: new Session(); $session->fill($sessionData); $session->save(); $sessionsIds[] = $session->id; } //##Delete the unused sessions //Getting all sessions ids $sessionsToRemove = array(); foreach ($report->sessions()->get() as $session) { $sessionsToRemove[] = $session->id; } //The ids that are different from sessionsIds, must be deleted $sessionsToRemove = array_diff($sessionsToRemove, $sessionsIds); foreach ($sessionsToRemove as $id) { Session::find($id)->delete(); } //##Inserting new sessions //Creating the new sessions $sessionsIds = array(); foreach ($request->input('new', array()) as $id => $sessionData) { $session = new Session(); $session->fill($sessionData); $session->monthly_report_id = $report->id; $session->save(); } } else { //If the student is absent, delete all recorded sessions foreach ($report->sessions()->get() as $session) { $session->delete(); } } //Sending the user to the monthly report return redirect()->route('monthlyreport/index'); }