namespace App\Http\Controllers\Api; use App\Models\Quiz; use App\Models\Question; use App\Models\Answer; use App\Models\Option; use App\Models\Test; use Illuminate\Http\Request; use App\Http\Controllers\Controller; class QuizController extends Controller { public function getQuestions(Quiz $quiz) { $questions = Question::whereHas('quizzes', function ($query) use ($quiz) { $query->where('id', $quiz->id); }) ->with('options') ->inRandomOrder() ->get(); return response()->json($questions); } public function submitQuiz(Request $request, Quiz $quiz) { $test = Test::create([ 'user_id' => auth()->id(), 'quiz_id' => $quiz->id, 'result' => 0, 'ip_address' => $request->ip(), 'time_spent' => $request->input('time_spent') ]); $result = 0; foreach ($request->input('answers') as $answer) { $optionId = $answer['option_id']; $questionId = $answer['question_id']; $correct = Option::find($optionId)->correct ?? false; if ($correct) { $result++; Answer::create([ 'user_id' => auth()->id(), 'test_id' => $test->id, 'question_id' => $questionId, 'option_id' => $optionId, 'correct' => 1 ]); } else { Answer::create([ 'user_id' => auth()->id(), 'test_id' => $test->id, 'question_id' => $questionId, 'option_id' => $optionId, 'correct' => 0 ]); } } $test->update(['result' => $result]); return response()->json(['result' => $result, 'test_id' => $test->id]); }