public function judgeApplication(Application $application, Request $request) { // Check if current user is allowed to score things $this->authorize('score-application'); if (!in_array($application->judge_status, ['new', 'ready'])) { $request->session()->flash('error', 'This application has already been finalized.'); return redirect('/applications/' . $application->id . '/review'); } // Check if the current user has already judged this application $judged = Judged::where(['application_id' => $application->id, 'user_id' => Auth::user()->id])->get()->first(); if (!empty($judged)) { $request->session()->flash('error', 'You have already judged this application!'); return redirect('/applications'); } else { $judged = new Judged(); $judged->application_id = $application->id; $judged->user_id = Auth::user()->id; $judged->save(); // Compare the total number of judges vs number of judges who have scored this application $totalJudges = User::where(['role' => 'judge'])->get(); $totalJudged = Judged::where(['application_id' => $application->id])->get(); // If at least half of the judges have rated this application, set it to ready if (ceil($totalJudged->count() / $totalJudges->count()) >= 0.5) { $application->judge_status = 'ready'; $application->save(); } // Calculate new scores Score::calculateTotals($application); $request->session()->flash('success', 'Your final scores have been submitted.'); return redirect('/applications'); } }