Phase 5: Quiz Form Type Implementation
Historical design/implementation plan. It is retained as background, not a statement that every proposed feature is available. Use the current component/project guides and the deployed editor before following its recipes.
Overview
This document details the implementation of the new "Quiz" form type, which enables assessments, trivia, and gamified knowledge checks with integration into the existing game/points system.
Feature Summary
- New Form Type:
quizform type for assessments - Question Configuration: Mark elements as questions with correct answers
- Randomization: Randomize questions and/or answers
- Timing System: Quiz-level and per-question timers
- Active Sections: Admin-controlled section progression for live quizzes
- Game Integration: Connect to existing Game/Points system
- Scoring with Multipliers: Per-question multipliers
- Trigger Integration: Quiz completion and answer events
1. Quiz Settings Configuration
QuizSettings Model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
class QuizSettings extends Model
{
protected $fillable = [
'project_form_id',
'game_id',
'create_game_session',
'randomize_questions',
'randomize_answers',
'question_limit',
'timed_quiz',
'quiz_time_limit',
'per_question_timer',
'default_question_time',
'active_section_id',
'section_progression_locked',
'default_points_correct',
'default_points_incorrect',
'allow_partial_credit',
'max_attempts',
'attempt_scoring',
'show_correct_answers',
'show_answers_when',
'show_score_during_quiz',
'show_leaderboard',
'leaderboard_type',
];
protected $casts = [
'create_game_session' => 'boolean',
'randomize_questions' => 'boolean',
'randomize_answers' => 'boolean',
'timed_quiz' => 'boolean',
'per_question_timer' => 'boolean',
'section_progression_locked' => 'boolean',
'allow_partial_credit' => 'boolean',
'show_correct_answers' => 'boolean',
'show_score_during_quiz' => 'boolean',
'show_leaderboard' => 'boolean',
];
public function projectForm(): BelongsTo
{
return $this->belongsTo(ProjectForm::class);
}
public function game(): BelongsTo
{
return $this->belongsTo(Game::class);
}
public function questionSettings(): HasMany
{
return $this->hasMany(QuizQuestionSettings::class, 'project_form_id', 'project_form_id');
}
public function attempts(): HasMany
{
return $this->hasMany(QuizAttempt::class, 'project_form_id', 'project_form_id');
}
/**
* Get questions for this quiz
*/
public function getQuestions(): Collection
{
$form = $this->projectForm;
// Get elements marked as quiz questions
if ($form->schema_version === 'v2') {
return collect($form->elements_config ?? [])
->filter(fn ($el) => $el['isQuizQuestion'] ?? false);
}
// v1: Get fields marked as quiz questions
return $form->fields()
->where('is_quiz_question', true)
->get();
}
/**
* Check if attendee can attempt quiz
*/
public function canAttempt(Attendee $attendee): bool
{
if (!$this->max_attempts) {
return true;
}
$attemptCount = $this->attempts()
->where('attendee_id', $attendee->id)
->whereIn('status', ['completed', 'timed_out'])
->count();
return $attemptCount < $this->max_attempts;
}
/**
* Get remaining attempts for attendee
*/
public function getRemainingAttempts(Attendee $attendee): ?int
{
if (!$this->max_attempts) {
return null; // Unlimited
}
$attemptCount = $this->attempts()
->where('attendee_id', $attendee->id)
->whereIn('status', ['completed', 'timed_out'])
->count();
return max(0, $this->max_attempts - $attemptCount);
}
/**
* Get attendee's best score based on scoring mode
*/
public function getAttendeeScore(Attendee $attendee): ?int
{
$attempts = $this->attempts()
->where('attendee_id', $attendee->id)
->whereIn('status', ['completed', 'timed_out'])
->get();
if ($attempts->isEmpty()) {
return null;
}
return match ($this->attempt_scoring) {
'highest' => $attempts->max('score'),
'latest' => $attempts->sortByDesc('completed_at')->first()->score,
'average' => (int) round($attempts->avg('score')),
'first' => $attempts->sortBy('attempt_number')->first()->score,
default => $attempts->max('score'),
};
}
/**
* Set active section for live quiz
*/
public function setActiveSection(?string $sectionId): void
{
$this->update(['active_section_id' => $sectionId]);
// Broadcast section change
broadcast(new QuizSectionChanged($this, $sectionId));
}
}
QuizQuestionSettings Model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class QuizQuestionSettings extends Model
{
protected $fillable = [
'project_form_id',
'element_id',
'question_type',
'correct_answers',
'case_sensitive',
'points_correct',
'points_incorrect',
'answer_multipliers',
'time_limit',
'feedback_correct',
'feedback_incorrect',
'answer_explanations',
];
protected $casts = [
'correct_answers' => 'array',
'case_sensitive' => 'boolean',
'answer_multipliers' => 'array',
'answer_explanations' => 'array',
];
public function projectForm(): BelongsTo
{
return $this->belongsTo(ProjectForm::class);
}
public function quizSettings(): BelongsTo
{
return $this->belongsTo(QuizSettings::class, 'project_form_id', 'project_form_id');
}
/**
* Check if answer is correct
*/
public function isCorrect(mixed $answer): bool
{
$correct = $this->correct_answers;
if (!$this->case_sensitive && is_string($answer)) {
$answer = strtolower($answer);
$correct = array_map('strtolower', $correct);
}
return match ($this->question_type) {
'single_choice' => in_array($answer, $correct),
'multiple_choice' => $this->checkMultipleChoice($answer, $correct),
'true_false' => in_array((string) $answer, $correct),
'text_match' => $this->checkTextMatch($answer, $correct),
'numeric_range' => $this->checkNumericRange($answer, $correct),
default => in_array($answer, $correct),
};
}
/**
* Calculate partial credit for multiple choice
*/
public function calculatePartialCredit(mixed $answer): float
{
if ($this->question_type !== 'multiple_choice' || !is_array($answer)) {
return $this->isCorrect($answer) ? 1.0 : 0.0;
}
$correct = $this->correct_answers;
$correctSelected = count(array_intersect($answer, $correct));
$incorrectSelected = count(array_diff($answer, $correct));
$totalCorrect = count($correct);
if ($totalCorrect === 0) {
return 0.0;
}
// Penalize incorrect selections
$score = ($correctSelected - ($incorrectSelected * 0.5)) / $totalCorrect;
return max(0.0, min(1.0, $score));
}
/**
* Get multiplier for specific answer
*/
public function getMultiplier(mixed $answer): float
{
if (!$this->answer_multipliers) {
return 1.0;
}
$key = is_array($answer) ? json_encode($answer) : (string) $answer;
return $this->answer_multipliers[$key] ?? 1.0;
}
/**
* Get points for this answer
*/
public function getPoints(mixed $answer, QuizSettings $settings): int
{
$basePoints = $this->isCorrect($answer)
? ($this->points_correct ?? $settings->default_points_correct)
: ($this->points_incorrect ?? $settings->default_points_incorrect);
// Apply partial credit if enabled
if ($settings->allow_partial_credit && !$this->isCorrect($answer)) {
$partial = $this->calculatePartialCredit($answer);
$maxPoints = $this->points_correct ?? $settings->default_points_correct;
$basePoints = (int) round($maxPoints * $partial);
}
// Apply multiplier
$multiplier = $this->getMultiplier($answer);
return (int) round($basePoints * $multiplier);
}
protected function checkMultipleChoice(mixed $answer, array $correct): bool
{
if (!is_array($answer)) {
return false;
}
sort($answer);
sort($correct);
return $answer === $correct;
}
protected function checkTextMatch(string $answer, array $correct): bool
{
foreach ($correct as $pattern) {
if (str_starts_with($pattern, '/') && str_ends_with($pattern, '/')) {
// Regex pattern
if (preg_match($pattern, $answer)) {
return true;
}
} elseif ($answer === $pattern) {
return true;
}
}
return false;
}
protected function checkNumericRange(mixed $answer, array $correct): bool
{
$value = floatval($answer);
if (isset($correct['min']) && $value < $correct['min']) {
return false;
}
if (isset($correct['max']) && $value > $correct['max']) {
return false;
}
if (isset($correct['exact'])) {
return abs($value - $correct['exact']) < 0.0001;
}
return true;
}
}
2. Quiz Attempt Tracking
QuizAttempt Model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
class QuizAttempt extends Model
{
protected $fillable = [
'project_form_id',
'attendee_id',
'game_session_id',
'attempt_number',
'status',
'total_questions',
'questions_answered',
'correct_answers',
'incorrect_answers',
'score',
'max_possible_score',
'percentage',
'started_at',
'completed_at',
'time_spent_seconds',
'question_order',
'metadata',
];
protected $casts = [
'started_at' => 'datetime',
'completed_at' => 'datetime',
'question_order' => 'array',
'metadata' => 'array',
'percentage' => 'decimal:2',
];
public function projectForm(): BelongsTo
{
return $this->belongsTo(ProjectForm::class);
}
public function attendee(): BelongsTo
{
return $this->belongsTo(Attendee::class);
}
public function gameSession(): BelongsTo
{
return $this->belongsTo(GameSession::class);
}
public function answers(): HasMany
{
return $this->hasMany(QuizAttemptAnswer::class);
}
/**
* Record an answer
*/
public function recordAnswer(
string $elementId,
mixed $answerValue,
QuizQuestionSettings $questionSettings,
QuizSettings $quizSettings
): QuizAttemptAnswer {
$isCorrect = $questionSettings->isCorrect($answerValue);
$partialCredit = $quizSettings->allow_partial_credit
? $questionSettings->calculatePartialCredit($answerValue)
: ($isCorrect ? 1.0 : 0.0);
$points = $questionSettings->getPoints($answerValue, $quizSettings);
$multiplier = $questionSettings->getMultiplier($answerValue);
$answer = $this->answers()->create([
'element_id' => $elementId,
'answer_value' => $answerValue,
'is_correct' => $isCorrect,
'partial_credit' => $partialCredit,
'points_awarded' => $points,
'multiplier_applied' => $multiplier,
'answered_at' => now(),
]);
// Update attempt totals
$this->updateTotals();
// Award points if game integrated
if ($quizSettings->game_id && $this->game_session_id) {
$this->awardGamePoints($answer, $questionSettings, $quizSettings);
}
return $answer;
}
/**
* Update attempt totals
*/
protected function updateTotals(): void
{
$answers = $this->answers()->get();
$this->update([
'questions_answered' => $answers->count(),
'correct_answers' => $answers->where('is_correct', true)->count(),
'incorrect_answers' => $answers->where('is_correct', false)->count(),
'score' => $answers->sum('points_awarded'),
]);
}
/**
* Complete the attempt
*/
public function complete(): void
{
$this->updateTotals();
$maxPossible = $this->calculateMaxPossibleScore();
$percentage = $maxPossible > 0
? ($this->score / $maxPossible) * 100
: 0;
$this->update([
'status' => 'completed',
'completed_at' => now(),
'max_possible_score' => $maxPossible,
'percentage' => round($percentage, 2),
'time_spent_seconds' => $this->started_at->diffInSeconds(now()),
]);
// Complete game session if applicable
if ($this->gameSession) {
app(GameSessionService::class)->update($this->gameSession, [
'status' => 'completed',
]);
}
// Dispatch completion event
event(new QuizAttemptCompleted($this));
}
/**
* Time out the attempt
*/
public function timeout(): void
{
$this->updateTotals();
$this->update([
'status' => 'timed_out',
'completed_at' => now(),
'time_spent_seconds' => $this->started_at->diffInSeconds(now()),
]);
event(new QuizAttemptTimedOut($this));
}
/**
* Calculate maximum possible score
*/
protected function calculateMaxPossibleScore(): int
{
$quizSettings = $this->projectForm->quizSettings;
$questionSettings = $quizSettings->questionSettings;
return $questionSettings->sum(function ($qs) use ($quizSettings) {
return $qs->points_correct ?? $quizSettings->default_points_correct;
});
}
/**
* Award points through game system
*/
protected function awardGamePoints(
QuizAttemptAnswer $answer,
QuizQuestionSettings $questionSettings,
QuizSettings $quizSettings
): void {
if ($answer->points_awarded <= 0) {
return;
}
$eventKey = $answer->is_correct
? 'quiz_question_correct'
: 'quiz_question_incorrect';
$pointTransaction = app(PointTransactionService::class)->create([
'game_id' => $quizSettings->game_id,
'attendee_id' => $this->attendee_id,
'game_session_id' => $this->game_session_id,
'points' => $answer->points_awarded,
'transaction_type' => 'awarded',
'event_key' => $eventKey,
'applied_multiplier' => $answer->multiplier_applied,
'idempotency_key' => "quiz_answer_{$answer->id}",
'metadata' => [
'quiz_attempt_id' => $this->id,
'element_id' => $answer->element_id,
'is_correct' => $answer->is_correct,
],
], $this->findPointRule($eventKey, $quizSettings));
$answer->update(['point_transaction_id' => $pointTransaction->id]);
}
protected function findPointRule(string $eventKey, QuizSettings $quizSettings): ?GamePointRule
{
return GamePointRule::where('game_id', $quizSettings->game_id)
->where('event_key', $eventKey)
->where('status', 'active')
->first();
}
}
3. Quiz Service
<?php
namespace App\Services\Quiz;
use App\Models\ProjectForm;
use App\Models\QuizSettings;
use App\Models\QuizAttempt;
use App\Models\Attendee;
use App\Models\GameSession;
use App\Services\GameSessionService;
use Illuminate\Support\Collection;
class QuizService
{
public function __construct(
protected GameSessionService $gameSessionService,
) {}
/**
* Start a new quiz attempt
*/
public function startAttempt(
ProjectForm $form,
Attendee $attendee
): QuizAttempt {
$settings = $form->quizSettings;
if (!$settings->canAttempt($attendee)) {
throw new \Exception('Maximum attempts reached for this quiz.');
}
// Get attempt number
$attemptNumber = QuizAttempt::where('project_form_id', $form->id)
->where('attendee_id', $attendee->id)
->count() + 1;
// Create game session if needed
$gameSession = null;
if ($settings->game_id && $settings->create_game_session) {
$gameSession = $this->gameSessionService->create($settings->game, [
'attendee_id' => $attendee->id,
]);
}
// Prepare question order
$questionOrder = $this->prepareQuestionOrder($settings);
return QuizAttempt::create([
'project_form_id' => $form->id,
'attendee_id' => $attendee->id,
'game_session_id' => $gameSession?->id,
'attempt_number' => $attemptNumber,
'status' => 'in_progress',
'total_questions' => count($questionOrder),
'started_at' => now(),
'question_order' => $questionOrder,
]);
}
/**
* Prepare question order with randomization
*/
protected function prepareQuestionOrder(QuizSettings $settings): array
{
$questions = $settings->getQuestions();
$questionIds = $questions->pluck('id')->toArray();
// Filter by active section if locked
if ($settings->section_progression_locked && $settings->active_section_id) {
$questionIds = $questions
->filter(fn ($q) => ($q['sectionId'] ?? null) === $settings->active_section_id)
->pluck('id')
->toArray();
}
// Randomize if enabled
if ($settings->randomize_questions) {
shuffle($questionIds);
}
// Limit questions if set
if ($settings->question_limit) {
$questionIds = array_slice($questionIds, 0, $settings->question_limit);
}
return $questionIds;
}
/**
* Submit answer for a question
*/
public function submitAnswer(
QuizAttempt $attempt,
string $elementId,
mixed $answerValue,
?int $timeSpent = null
): array {
if ($attempt->status !== 'in_progress') {
throw new \Exception('Quiz attempt is not in progress.');
}
$settings = $attempt->projectForm->quizSettings;
$questionSettings = $settings->questionSettings()
->where('element_id', $elementId)
->first();
if (!$questionSettings) {
throw new \Exception('Question not found.');
}
// Check for timeout
if ($settings->timed_quiz && $settings->quiz_time_limit) {
$elapsed = $attempt->started_at->diffInSeconds(now());
if ($elapsed > $settings->quiz_time_limit) {
$attempt->timeout();
return [
'success' => false,
'reason' => 'timeout',
'message' => 'Quiz time limit exceeded.',
];
}
}
// Record answer
$answer = $attempt->recordAnswer(
$elementId,
$answerValue,
$questionSettings,
$settings
);
// Prepare response
$response = [
'success' => true,
'is_correct' => $answer->is_correct,
'points_awarded' => $answer->points_awarded,
];
// Include feedback if configured
if ($settings->show_correct_answers && $settings->show_answers_when === 'immediately') {
$response['correct_answer'] = $questionSettings->correct_answers;
$response['feedback'] = $answer->is_correct
? $questionSettings->feedback_correct
: $questionSettings->feedback_incorrect;
$response['explanation'] = $questionSettings->answer_explanations[$answerValue] ?? null;
}
// Include score if configured
if ($settings->show_score_during_quiz) {
$response['current_score'] = $attempt->score;
$response['questions_answered'] = $attempt->questions_answered;
$response['correct_answers'] = $attempt->correct_answers;
}
return $response;
}
/**
* Complete quiz attempt
*/
public function completeAttempt(QuizAttempt $attempt): array
{
$attempt->complete();
$settings = $attempt->projectForm->quizSettings;
$result = [
'success' => true,
'score' => $attempt->score,
'max_score' => $attempt->max_possible_score,
'percentage' => $attempt->percentage,
'correct_answers' => $attempt->correct_answers,
'incorrect_answers' => $attempt->incorrect_answers,
'time_spent' => $attempt->time_spent_seconds,
];
// Include correct answers if configured
if ($settings->show_correct_answers &&
in_array($settings->show_answers_when, ['after_submit', 'immediately'])) {
$result['answers'] = $this->getAnswerReview($attempt);
}
// Include leaderboard position if configured
if ($settings->show_leaderboard && $settings->game_id) {
$result['leaderboard_position'] = $this->getLeaderboardPosition($attempt);
}
return $result;
}
/**
* Get answer review for completed attempt
*/
protected function getAnswerReview(QuizAttempt $attempt): array
{
$questionSettings = $attempt->projectForm->quizSettings->questionSettings->keyBy('element_id');
return $attempt->answers->map(function ($answer) use ($questionSettings) {
$qs = $questionSettings[$answer->element_id] ?? null;
return [
'element_id' => $answer->element_id,
'your_answer' => $answer->answer_value,
'correct_answer' => $qs?->correct_answers,
'is_correct' => $answer->is_correct,
'points' => $answer->points_awarded,
'feedback' => $answer->is_correct
? $qs?->feedback_correct
: $qs?->feedback_incorrect,
];
})->toArray();
}
/**
* Get leaderboard position
*/
protected function getLeaderboardPosition(QuizAttempt $attempt): ?int
{
$settings = $attempt->projectForm->quizSettings;
if (!$settings->game_id) {
return null;
}
$leaderboard = app(LeaderboardService::class)
->getLeaderboard($settings->game_id, $settings->leaderboard_type);
$position = 1;
foreach ($leaderboard as $entry) {
if ($entry['attendee_id'] === $attempt->attendee_id) {
return $position;
}
$position++;
}
return null;
}
/**
* Get quiz state for attendee
*/
public function getQuizState(ProjectForm $form, Attendee $attendee): array
{
$settings = $form->quizSettings;
// Check for in-progress attempt
$activeAttempt = QuizAttempt::where('project_form_id', $form->id)
->where('attendee_id', $attendee->id)
->where('status', 'in_progress')
->first();
if ($activeAttempt) {
// Check for timeout
if ($settings->timed_quiz && $settings->quiz_time_limit) {
$elapsed = $activeAttempt->started_at->diffInSeconds(now());
if ($elapsed > $settings->quiz_time_limit) {
$activeAttempt->timeout();
$activeAttempt = null;
}
}
}
return [
'can_attempt' => $settings->canAttempt($attendee),
'remaining_attempts' => $settings->getRemainingAttempts($attendee),
'best_score' => $settings->getAttendeeScore($attendee),
'active_attempt' => $activeAttempt ? [
'id' => $activeAttempt->id,
'started_at' => $activeAttempt->started_at,
'questions_answered' => $activeAttempt->questions_answered,
'total_questions' => $activeAttempt->total_questions,
'current_score' => $settings->show_score_during_quiz ? $activeAttempt->score : null,
'time_remaining' => $settings->timed_quiz && $settings->quiz_time_limit
? max(0, $settings->quiz_time_limit - $activeAttempt->started_at->diffInSeconds(now()))
: null,
] : null,
'active_section' => $settings->active_section_id,
'section_locked' => $settings->section_progression_locked,
];
}
}
4. Trigger Integration
Quiz Events
<?php
// app/Events/QuizAttemptCompleted.php
namespace App\Events;
use App\Models\QuizAttempt;
use App\Events\Contracts\AdminWorkflowTriggerInterface;
use Illuminate\Contracts\Events\ShouldDispatchAfterCommit;
class QuizAttemptCompleted implements AdminWorkflowTriggerInterface, ShouldDispatchAfterCommit
{
public function __construct(
public QuizAttempt $attempt,
) {}
public function getAttendeeId(): ?int
{
return $this->attempt->attendee_id;
}
public function getProjectId(): int
{
return $this->attempt->projectForm->project_id;
}
public function getModel(): object
{
return $this->attempt;
}
public function getReferenceData(): array
{
return [
QuizAttempt::class => [
'id' => $this->attempt->id,
'score' => $this->attempt->score,
'percentage' => $this->attempt->percentage,
'correct_answers' => $this->attempt->correct_answers,
'time_spent' => $this->attempt->time_spent_seconds,
],
ProjectForm::class => $this->attempt->projectForm->toNotificationReferenceData(),
Attendee::class => $this->attempt->attendee->toNotificationReferenceData(),
];
}
public function getIdempotencyKey(): ?string
{
return "quiz_completed_{$this->attempt->id}";
}
public function shouldSendNotifications(): bool
{
return true;
}
}
<?php
// app/Events/QuizQuestionAnswered.php
namespace App\Events;
use App\Models\QuizAttemptAnswer;
use App\Models\QuizAttempt;
use App\Events\Contracts\AdminWorkflowTriggerInterface;
use Illuminate\Contracts\Events\ShouldDispatchAfterCommit;
class QuizQuestionAnswered implements AdminWorkflowTriggerInterface, ShouldDispatchAfterCommit
{
public function __construct(
public QuizAttemptAnswer $answer,
public QuizAttempt $attempt,
) {}
public function getAttendeeId(): ?int
{
return $this->attempt->attendee_id;
}
public function getProjectId(): int
{
return $this->attempt->projectForm->project_id;
}
public function getModel(): object
{
return $this->answer;
}
public function getReferenceData(): array
{
return [
QuizAttemptAnswer::class => [
'id' => $this->answer->id,
'element_id' => $this->answer->element_id,
'is_correct' => $this->answer->is_correct,
'points_awarded' => $this->answer->points_awarded,
],
QuizAttempt::class => [
'id' => $this->attempt->id,
'current_score' => $this->attempt->score,
],
];
}
public function getIdempotencyKey(): ?string
{
return "quiz_answer_{$this->answer->id}";
}
public function shouldSendNotifications(): bool
{
return false; // Don't send notifications per question
}
}
Register Events in AdminWorkflowTrigger
// app/Models/AdminWorkflowTrigger.php
public static function getAvailableEventTypes(): array
{
return [
// ... existing events ...
// Quiz Events
QuizAttemptCompleted::class => [
'label' => 'Quiz Completed',
'model_event' => 'QuizAttempt.completed',
'scope_by_group_membership' => true,
'exact_group_match_required' => false,
'trigger_conditions_required' => true, // Can filter by score
'valid_for_gamification' => true,
],
QuizQuestionAnswered::class => [
'label' => 'Quiz Question Answered',
'model_event' => 'QuizAttemptAnswer.created',
'scope_by_group_membership' => true,
'exact_group_match_required' => false,
'trigger_conditions_required' => true, // Can filter by correct/incorrect
'valid_for_gamification' => true,
],
];
}
5. Frontend Quiz Components
Quiz Renderer Component
<!-- resources/js/Components/Quiz/QuizRenderer.vue -->
<script setup>
import { ref, computed, watch, onMounted, onUnmounted } from 'vue'
import { usePage } from '@inertiajs/vue3'
import ModCard from '@/Components/Mod/v2/Cards/ModCard.vue'
import ModButton from '@/Components/Mod/v2/Elements/ModButton.vue'
import ModProgress from '@/Components/Mod/v2/Display/ModProgress.vue'
import QuizQuestion from './QuizQuestion.vue'
import QuizTimer from './QuizTimer.vue'
import QuizResults from './QuizResults.vue'
const props = defineProps({
form: { type: Object, required: true },
settings: { type: Object, required: true },
initialState: { type: Object, default: null },
})
const emit = defineEmits(['completed', 'timeout'])
const state = ref('ready') // ready, in_progress, completed, timed_out
const attempt = ref(null)
const currentQuestionIndex = ref(0)
const answers = ref({})
const results = ref(null)
const loading = ref(false)
// Timer state
const timeRemaining = ref(null)
const questionTimeRemaining = ref(null)
// Questions from form
const questions = computed(() => {
if (!attempt.value?.question_order) {
return props.form.elements.filter(el => el.isQuizQuestion)
}
const order = attempt.value.question_order
return order.map(id => props.form.elements.find(el => el.id === id)).filter(Boolean)
})
const currentQuestion = computed(() => questions.value[currentQuestionIndex.value])
const progress = computed(() => {
if (!questions.value.length) return 0
return Math.round((currentQuestionIndex.value / questions.value.length) * 100)
})
// Initialize from existing state
onMounted(() => {
if (props.initialState?.active_attempt) {
attempt.value = props.initialState.active_attempt
state.value = 'in_progress'
if (props.initialState.active_attempt.time_remaining !== null) {
timeRemaining.value = props.initialState.active_attempt.time_remaining
}
}
})
// Quiz timer
let timerInterval = null
watch(() => state.value, (newState) => {
if (newState === 'in_progress' && props.settings.timed_quiz) {
startTimer()
} else {
clearInterval(timerInterval)
}
})
const startTimer = () => {
if (timerInterval) clearInterval(timerInterval)
timerInterval = setInterval(() => {
if (timeRemaining.value !== null) {
timeRemaining.value--
if (timeRemaining.value <= 0) {
handleTimeout()
}
}
if (questionTimeRemaining.value !== null) {
questionTimeRemaining.value--
if (questionTimeRemaining.value <= 0) {
// Auto-submit current question
submitAnswer()
}
}
}, 1000)
}
onUnmounted(() => {
clearInterval(timerInterval)
})
// Start quiz
const startQuiz = async () => {
loading.value = true
try {
const response = await axios.post(route('portal.quiz.start', {
form: props.form.slug,
}))
attempt.value = response.data.attempt
state.value = 'in_progress'
if (props.settings.quiz_time_limit) {
timeRemaining.value = props.settings.quiz_time_limit
}
if (props.settings.per_question_timer) {
resetQuestionTimer()
}
} catch (error) {
console.error('Failed to start quiz:', error)
} finally {
loading.value = false
}
}
// Submit answer
const submitAnswer = async (answerValue = null) => {
const value = answerValue ?? answers.value[currentQuestion.value.id]
loading.value = true
try {
const response = await axios.post(route('portal.quiz.answer', {
form: props.form.slug,
attempt: attempt.value.id,
}), {
element_id: currentQuestion.value.id,
answer: value,
})
// Update local state with server response
if (response.data.current_score !== undefined) {
attempt.value.score = response.data.current_score
}
// Show feedback if immediate
if (response.data.feedback) {
// Handle feedback display
}
// Move to next question or complete
if (currentQuestionIndex.value < questions.value.length - 1) {
currentQuestionIndex.value++
resetQuestionTimer()
} else {
await completeQuiz()
}
} catch (error) {
if (error.response?.data?.reason === 'timeout') {
handleTimeout()
} else {
console.error('Failed to submit answer:', error)
}
} finally {
loading.value = false
}
}
const resetQuestionTimer = () => {
if (!props.settings.per_question_timer) return
const questionSettings = props.settings.question_settings?.[currentQuestion.value.id]
questionTimeRemaining.value = questionSettings?.time_limit ?? props.settings.default_question_time
}
// Complete quiz
const completeQuiz = async () => {
loading.value = true
try {
const response = await axios.post(route('portal.quiz.complete', {
form: props.form.slug,
attempt: attempt.value.id,
}))
results.value = response.data
state.value = 'completed'
emit('completed', response.data)
} catch (error) {
console.error('Failed to complete quiz:', error)
} finally {
loading.value = false
}
}
// Handle timeout
const handleTimeout = async () => {
state.value = 'timed_out'
clearInterval(timerInterval)
try {
const response = await axios.post(route('portal.quiz.timeout', {
form: props.form.slug,
attempt: attempt.value.id,
}))
results.value = response.data
emit('timeout', response.data)
} catch (error) {
console.error('Failed to process timeout:', error)
}
}
</script>
<template>
<div class="quiz-renderer">
<!-- Ready State -->
<ModCard v-if="state === 'ready'" class="text-center py-5">
<h2>{{ form.name }}</h2>
<p class="text-muted">{{ form.description }}</p>
<div class="quiz-info my-4">
<div class="row justify-content-center g-4">
<div class="col-auto">
<div class="text-muted small">Questions</div>
<div class="h4">{{ questions.length }}</div>
</div>
<div v-if="settings.quiz_time_limit" class="col-auto">
<div class="text-muted small">Time Limit</div>
<div class="h4">{{ Math.floor(settings.quiz_time_limit / 60) }} min</div>
</div>
<div v-if="settings.max_attempts" class="col-auto">
<div class="text-muted small">Attempts</div>
<div class="h4">{{ initialState?.remaining_attempts ?? settings.max_attempts }}</div>
</div>
</div>
</div>
<div v-if="initialState?.best_score !== null" class="mb-4">
<span class="badge bg-info">Your Best Score: {{ initialState.best_score }}</span>
</div>
<ModButton
v-if="initialState?.can_attempt !== false"
color="primary"
size="lg"
:disabled="loading"
@click="startQuiz"
>
<span v-if="loading" class="spinner-border spinner-border-sm me-2" />
{{ initialState?.active_attempt ? 'Resume Quiz' : 'Start Quiz' }}
</ModButton>
<p v-else class="text-danger mt-3">
You have reached the maximum number of attempts.
</p>
</ModCard>
<!-- In Progress State -->
<template v-else-if="state === 'in_progress'">
<!-- Header with progress and timer -->
<div class="quiz-header mb-4">
<div class="d-flex justify-content-between align-items-center">
<div>
Question {{ currentQuestionIndex + 1 }} of {{ questions.length }}
</div>
<div class="d-flex gap-3">
<QuizTimer
v-if="timeRemaining !== null"
:seconds="timeRemaining"
label="Quiz Time"
:warning-threshold="60"
/>
<QuizTimer
v-if="questionTimeRemaining !== null"
:seconds="questionTimeRemaining"
label="Question"
:warning-threshold="10"
/>
</div>
</div>
<ModProgress :value="progress" class="mt-2" />
</div>
<!-- Current Score (if enabled) -->
<div v-if="settings.show_score_during_quiz" class="mb-3 text-end">
<span class="badge bg-primary">Score: {{ attempt.score }}</span>
</div>
<!-- Question -->
<QuizQuestion
v-if="currentQuestion"
:question="currentQuestion"
:question-settings="settings.question_settings?.[currentQuestion.id]"
:randomize-answers="settings.randomize_answers"
v-model="answers[currentQuestion.id]"
:disabled="loading"
@submit="submitAnswer"
/>
<!-- Navigation -->
<div class="quiz-nav d-flex justify-content-between mt-4">
<ModButton
v-if="currentQuestionIndex > 0 && !settings.section_progression_locked"
color="secondary"
outline
@click="currentQuestionIndex--"
>
Previous
</ModButton>
<div v-else />
<ModButton
color="primary"
:disabled="loading || !answers[currentQuestion?.id]"
@click="submitAnswer()"
>
<span v-if="loading" class="spinner-border spinner-border-sm me-2" />
{{ currentQuestionIndex === questions.length - 1 ? 'Finish Quiz' : 'Next' }}
</ModButton>
</div>
</template>
<!-- Results State -->
<QuizResults
v-else-if="state === 'completed' || state === 'timed_out'"
:results="results"
:timed-out="state === 'timed_out'"
:show-answers="settings.show_correct_answers"
:show-leaderboard="settings.show_leaderboard"
@retry="state = 'ready'"
/>
</div>
</template>
Quiz Question Component
<!-- resources/js/Components/Quiz/QuizQuestion.vue -->
<script setup>
import { ref, computed, watch } from 'vue'
import ModCard from '@/Components/Mod/v2/Cards/ModCard.vue'
import ModRadioGroup from '@/Components/Mod/v2/Elements/OptionSelect/ModRadioGroup.vue'
import ModCheckboxGroup from '@/Components/Mod/v2/Elements/OptionSelect/ModCheckboxGroup.vue'
import ModInput from '@/Components/Mod/v2/Elements/Inputs/ModInput.vue'
import ModSwitch from '@/Components/Mod/v2/Elements/Boolean/ModSwitch.vue'
const props = defineProps({
question: { type: Object, required: true },
questionSettings: { type: Object, default: null },
randomizeAnswers: { type: Boolean, default: false },
modelValue: { type: [String, Number, Array, Boolean], default: null },
disabled: { type: Boolean, default: false },
showFeedback: { type: Boolean, default: false },
feedback: { type: Object, default: null },
})
const emit = defineEmits(['update:modelValue', 'submit'])
const localValue = ref(props.modelValue)
watch(() => props.modelValue, (val) => {
localValue.value = val
})
watch(localValue, (val) => {
emit('update:modelValue', val)
})
// Randomize options if enabled
const options = computed(() => {
let opts = props.question.options || []
if (props.randomizeAnswers && opts.length > 0) {
opts = [...opts].sort(() => Math.random() - 0.5)
}
return opts
})
// Determine question input type
const questionType = computed(() => {
return props.questionSettings?.question_type || inferQuestionType()
})
const inferQuestionType = () => {
if (props.question.type === 'boolean') return 'true_false'
if (props.question.style === 'checkbox') return 'multiple_choice'
if (props.question.options?.length > 0) return 'single_choice'
return 'text_match'
}
</script>
<template>
<ModCard class="quiz-question">
<div class="question-content mb-4">
<h4>{{ question.label || question.content }}</h4>
<p v-if="question.description" class="text-muted">
{{ question.description }}
</p>
</div>
<!-- Single Choice (Radio) -->
<ModRadioGroup
v-if="questionType === 'single_choice'"
v-model="localValue"
:options="options"
:disabled="disabled"
stacked
/>
<!-- Multiple Choice (Checkbox) -->
<ModCheckboxGroup
v-else-if="questionType === 'multiple_choice'"
v-model="localValue"
:options="options"
:disabled="disabled"
/>
<!-- True/False -->
<div v-else-if="questionType === 'true_false'" class="d-flex gap-3">
<ModSwitch
v-model="localValue"
:disabled="disabled"
true-label="True"
false-label="False"
/>
</div>
<!-- Text Match -->
<ModInput
v-else-if="questionType === 'text_match'"
v-model="localValue"
:disabled="disabled"
placeholder="Enter your answer..."
@keyup.enter="emit('submit')"
/>
<!-- Numeric -->
<ModInput
v-else-if="questionType === 'numeric_range'"
v-model.number="localValue"
type="number"
:disabled="disabled"
@keyup.enter="emit('submit')"
/>
<!-- Feedback (shown after answer) -->
<div v-if="showFeedback && feedback" class="mt-4">
<div
class="alert"
:class="feedback.is_correct ? 'alert-success' : 'alert-danger'"
>
<strong>{{ feedback.is_correct ? 'Correct!' : 'Incorrect' }}</strong>
<p v-if="feedback.message" class="mb-0 mt-1">{{ feedback.message }}</p>
</div>
</div>
</ModCard>
</template>
6. Admin Quiz Configuration UI
ShowPage Tab Configuration
// Quiz Settings tab for ProjectForm Show.vue
const quizSettingsTab = {
title: 'Quiz Settings',
tabId: 'quiz_settings',
condition: {
field: 'form_type',
operator: '==',
value: 'quiz',
},
cards: [
{
type: 'fields_list',
title: 'Game Integration',
icon: 'gamepad',
fieldsList: [
{
type: 'async-select',
name: 'quiz_settings.game_id',
label: 'Connect to Game',
description: 'Link quiz scores to the game/points system',
asyncRoute: 'api.games.search',
clearable: true,
colsMd: 6,
},
{
type: 'boolean',
style: 'switch',
name: 'quiz_settings.create_game_session',
label: 'Create Game Session',
description: 'Create a game session for each quiz attempt',
default: true,
condition: {
field: 'quiz_settings.game_id',
operator: '!=',
value: null,
},
colsMd: 6,
},
],
},
{
type: 'fields_list',
title: 'Randomization',
icon: 'shuffle',
fieldsList: [
{
type: 'boolean',
style: 'switch',
name: 'quiz_settings.randomize_questions',
label: 'Randomize Question Order',
colsMd: 4,
},
{
type: 'boolean',
style: 'switch',
name: 'quiz_settings.randomize_answers',
label: 'Randomize Answer Order',
colsMd: 4,
},
{
type: 'input',
style: 'number',
name: 'quiz_settings.question_limit',
label: 'Question Limit',
description: 'Max questions to show (blank = all)',
min: 1,
colsMd: 4,
},
],
},
{
type: 'fields_list',
title: 'Timing',
icon: 'clock',
fieldsList: [
{
type: 'boolean',
style: 'switch',
name: 'quiz_settings.timed_quiz',
label: 'Enable Quiz Timer',
colsMd: 6,
},
{
type: 'input',
style: 'number',
name: 'quiz_settings.quiz_time_limit',
label: 'Time Limit (seconds)',
condition: {
field: 'quiz_settings.timed_quiz',
operator: '==',
value: true,
},
colsMd: 6,
},
{
type: 'boolean',
style: 'switch',
name: 'quiz_settings.per_question_timer',
label: 'Per-Question Timer',
colsMd: 6,
},
{
type: 'input',
style: 'number',
name: 'quiz_settings.default_question_time',
label: 'Default Time per Question (seconds)',
condition: {
field: 'quiz_settings.per_question_timer',
operator: '==',
value: true,
},
colsMd: 6,
},
],
},
{
type: 'fields_list',
title: 'Scoring',
icon: 'star',
fieldsList: [
{
type: 'input',
style: 'number',
name: 'quiz_settings.default_points_correct',
label: 'Points for Correct Answer',
default: 10,
colsMd: 4,
},
{
type: 'input',
style: 'number',
name: 'quiz_settings.default_points_incorrect',
label: 'Points for Incorrect Answer',
default: 0,
colsMd: 4,
},
{
type: 'boolean',
style: 'switch',
name: 'quiz_settings.allow_partial_credit',
label: 'Allow Partial Credit',
description: 'For multiple choice questions',
colsMd: 4,
},
],
},
{
type: 'fields_list',
title: 'Attempts',
icon: 'repeat',
fieldsList: [
{
type: 'input',
style: 'number',
name: 'quiz_settings.max_attempts',
label: 'Max Attempts',
description: 'Blank = unlimited',
min: 1,
colsMd: 6,
},
{
type: 'option-select',
style: 'select',
name: 'quiz_settings.attempt_scoring',
label: 'Score Selection',
options: [
{ value: 'highest', label: 'Highest Score' },
{ value: 'latest', label: 'Latest Attempt' },
{ value: 'average', label: 'Average' },
{ value: 'first', label: 'First Attempt' },
],
default: 'highest',
colsMd: 6,
},
],
},
{
type: 'fields_list',
title: 'Display Settings',
icon: 'eye',
fieldsList: [
{
type: 'boolean',
style: 'switch',
name: 'quiz_settings.show_correct_answers',
label: 'Show Correct Answers',
colsMd: 6,
},
{
type: 'option-select',
style: 'select',
name: 'quiz_settings.show_answers_when',
label: 'Show Answers When',
options: [
{ value: 'immediately', label: 'After Each Question' },
{ value: 'after_submit', label: 'After Quiz Submission' },
{ value: 'after_deadline', label: 'After Quiz Closes' },
{ value: 'never', label: 'Never' },
],
default: 'after_submit',
condition: {
field: 'quiz_settings.show_correct_answers',
operator: '==',
value: true,
},
colsMd: 6,
},
{
type: 'boolean',
style: 'switch',
name: 'quiz_settings.show_score_during_quiz',
label: 'Show Score During Quiz',
colsMd: 6,
},
{
type: 'boolean',
style: 'switch',
name: 'quiz_settings.show_leaderboard',
label: 'Show Leaderboard',
colsMd: 6,
},
],
},
{
type: 'fields_list',
title: 'Live Quiz Controls',
icon: 'broadcast-tower',
description: 'Control which section is active for live quiz events',
fieldsList: [
{
type: 'boolean',
style: 'switch',
name: 'quiz_settings.section_progression_locked',
label: 'Lock Section Progression',
description: 'Only allow answers in the active section',
colsMd: 6,
},
{
type: 'option-select',
style: 'select',
name: 'quiz_settings.active_section_id',
label: 'Active Section',
options: sectionOptions, // Dynamically populated
clearable: true,
colsMd: 6,
},
],
},
],
}
API Endpoints
Quiz API Routes
// routes/portal/app.php
Route::prefix('quiz/{form}')->group(function () {
Route::get('state', [QuizController::class, 'state']);
Route::post('start', [QuizController::class, 'start']);
Route::post('attempts/{attempt}/answer', [QuizController::class, 'answer']);
Route::post('attempts/{attempt}/complete', [QuizController::class, 'complete']);
Route::post('attempts/{attempt}/timeout', [QuizController::class, 'timeout']);
Route::get('leaderboard', [QuizController::class, 'leaderboard']);
});
// Admin routes
Route::prefix('project-forms/{form}/quiz')->group(function () {
Route::get('settings', [QuizSettingsController::class, 'show']);
Route::put('settings', [QuizSettingsController::class, 'update']);
Route::get('questions', [QuizSettingsController::class, 'questions']);
Route::put('questions/{element_id}', [QuizSettingsController::class, 'updateQuestion']);
Route::post('set-active-section', [QuizSettingsController::class, 'setActiveSection']);
Route::get('attempts', [QuizSettingsController::class, 'attempts']);
Route::get('analytics', [QuizSettingsController::class, 'analytics']);
});
WebSocket Events
Quiz Section Changed Event
<?php
namespace App\Events;
use App\Models\QuizSettings;
use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
class QuizSectionChanged implements ShouldBroadcast
{
use InteractsWithSockets;
public function __construct(
public QuizSettings $quiz,
public ?string $activeSectionId,
) {}
public function broadcastOn(): array
{
return [
new Channel("quiz.{$this->quiz->project_form_id}"),
];
}
public function broadcastAs(): string
{
return 'section.changed';
}
public function broadcastWith(): array
{
return [
'quiz_id' => $this->quiz->project_form_id,
'active_section_id' => $this->activeSectionId,
];
}
}
Next Steps
- 06-PORTAL-INTEGRATION.md - Portal authentication and form embedding
- 07-ASSET-MANAGEMENT.md - Attendee asset table with security features