/** * @param $id * @throws GeneralException * @return mixed */ public function init($id) { $task = $this->findOrThrowException($id); if ($task->isEditable()) { $poll = $task->poll; $questionsNumber = $poll->questions_number; $questionsCategory = $poll->category; /** @var Category $questionsCategory */ $categories = $questionsCategory->getDescendantsAndSelf()->pluck('id'); $questions = Question::with('categories')->whereHas('categories', function ($q) use($categories) { $q->whereIn('categories.id', $categories); })->orderByRaw("RAND()")->take($questionsNumber)->get(); if ($questions->count() == $questionsNumber) { /** @var Question $question */ foreach ($questions as $question) { $task->userAnswers()->create(['question_id' => $question->id]); } $task->status = Task::STATUS_IN_PROGRESS; $task->started_at = Carbon::now(); $task->save(); return true; } throw new GeneralException(trans('exceptions.frontend.quiz.tasks.not_possible_to_init')); } }