'datetime', 'is_completed' => 'boolean', ]; /** * Generating empty answers to fill later * @param Collection|array $questions * @return void */ public function generateEmptyAnswers(Collection|array $questions) { $answers = []; foreach ($questions as $question) { $questionId = is_array($question) ? $question['id'] : $question->id; $answers[] = [ 'question_id' => $questionId, 'user_test_id' => $this->id, 'user_id' => $this->user_id, 'created_at' => now(), 'updated_at' => now(), ]; } UserTestAnswer::insert($answers); } public function completeTest() { $correctAnswers = 0; $allAnswers = $this->answers->count(); foreach ($this->answers as $answer) { if($answer->isCorrect()) $correctAnswers++; } $this->score = intval($correctAnswers * 100 / $allAnswers); $this->is_completed = true; $this->save(); } /** * Check cooldown for current test * @return bool */ public function isAvailable() { return (!$this->is_completed) && ($this->closed_at === null || now()->lt($this->closed_at)); } public function category() { return $this->belongsTo(Category::class); } public function test() { return $this->belongsTo(Test::class); } public function user() { return $this->belongsTo(User::class); } public function answers() { return $this->hasMany(UserTestAnswer::class); } }