Muhammad Fari Madyan
Hire me
Laravel · part 3 of 11

Laravel E-Learning Part 3: Database Schema Design

Designing a robust database schema for an e-learning platform with users, subjects, exams, questions, and results using Laravel migrations.

Muhammad Fari Madyan

· 4 min read

Baca dalam Bahasa Indonesia →

Entity Relationship Overview

Before writing any code, let's look at the data model:

Entity Relationship Diagram

Tables Overview

TableDescriptionKey Relationships
usersAll users (Admin, Teacher, Student)Has roles via Spatie
subjectsCourse subjects (Math, Physics, etc.)Belongs to Teacher
examsIndividual exams/testsBelongs to Subject, has many Questions
questionsExam questionsBelongs to Exam
exam_attemptsA student's exam sessionBelongs to Exam and Student
answersA student's answersBelongs to ExamAttempt and Question

Laravel Eloquent Relationships

ModelRelationshipRelated Model
User (Teacher)hasManySubject
SubjectbelongsToUser
SubjecthasManyExam
ExambelongsToSubject
ExamhasManyQuestion
ExamhasManyExamAttempt
QuestionbelongsToExam
ExamAttemptbelongsToUser (Student)
ExamAttemptbelongsToExam
ExamAttempthasManyAnswer
AnswerbelongsToExamAttempt
AnswerbelongsToQuestion

Step 1: Create Migrations

Subjects Table

BASH
php artisan make:migration create_subjects_table
PHP
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('subjects', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('code')->unique();
            $table->text('description')->nullable();
            $table->foreignId('teacher_id')->constrained('users')->onDelete('cascade');
            $table->boolean('is_active')->default(true);
            $table->timestamps();
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('subjects');
    }
};

Exams Table

BASH
php artisan make:migration create_exams_table
PHP
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('exams', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->text('description')->nullable();
            $table->foreignId('subject_id')->constrained()->onDelete('cascade');
            $table->integer('duration_minutes')->default(60);
            $table->integer('passing_score')->default(60);
            $table->integer('total_questions')->default(0);
            $table->dateTime('start_time');
            $table->dateTime('end_time');
            $table->enum('status', ['draft', 'published', 'closed'])->default('draft');
            $table->boolean('shuffle_questions')->default(false);
            $table->boolean('show_result')->default(true);
            $table->timestamps();
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('exams');
    }
};

Questions Table

BASH
php artisan make:migration create_questions_table
PHP
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('questions', function (Blueprint $table) {
            $table->id();
            $table->foreignId('exam_id')->constrained()->onDelete('cascade');
            $table->text('question_text');
            $table->enum('question_type', ['multiple_choice', 'true_false', 'essay'])->default('multiple_choice');
            $table->json('options')->nullable(); // For multiple choice
            $table->string('correct_answer');
            $table->integer('points')->default(1);
            $table->integer('order')->default(0);
            $table->timestamps();
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('questions');
    }
};

Exam Attempts Table

BASH
php artisan make:migration create_exam_attempts_table
PHP
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('exam_attempts', function (Blueprint $table) {
            $table->id();
            $table->foreignId('exam_id')->constrained()->onDelete('cascade');
            $table->foreignId('student_id')->constrained('users')->onDelete('cascade');
            $table->dateTime('started_at');
            $table->dateTime('completed_at')->nullable();
            $table->integer('score')->nullable();
            $table->integer('correct_answers')->default(0);
            $table->integer('total_answered')->default(0);
            $table->enum('status', ['in_progress', 'completed', 'timed_out'])->default('in_progress');
            $table->timestamps();
            
            $table->unique(['exam_id', 'student_id']);
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('exam_attempts');
    }
};

Answers Table

BASH
php artisan make:migration create_answers_table
PHP
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('answers', function (Blueprint $table) {
            $table->id();
            $table->foreignId('exam_attempt_id')->constrained()->onDelete('cascade');
            $table->foreignId('question_id')->constrained()->onDelete('cascade');
            $table->text('answer')->nullable();
            $table->boolean('is_correct')->nullable();
            $table->integer('points_earned')->default(0);
            $table->timestamps();
            
            $table->unique(['exam_attempt_id', 'question_id']);
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('answers');
    }
};

Step 2: Create Models

Subject Model

BASH
php artisan make:model Subject
PHP
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;

class Subject extends Model
{
    use HasFactory;

    protected $fillable = [
        'name',
        'code',
        'description',
        'teacher_id',
        'is_active',
    ];

    protected $casts = [
        'is_active' => 'boolean',
    ];

    public function teacher(): BelongsTo
    {
        return $this->belongsTo(User::class, 'teacher_id');
    }

    public function exams(): HasMany
    {
        return $this->hasMany(Exam::class);
    }
}

Exam Model

PHP
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;

class Exam extends Model
{
    use HasFactory;

    protected $fillable = [
        'title',
        'description',
        'subject_id',
        'duration_minutes',
        'passing_score',
        'total_questions',
        'start_time',
        'end_time',
        'status',
        'shuffle_questions',
        'show_result',
    ];

    protected $casts = [
        'start_time' => 'datetime',
        'end_time' => 'datetime',
        'shuffle_questions' => 'boolean',
        'show_result' => 'boolean',
    ];

    public function subject(): BelongsTo
    {
        return $this->belongsTo(Subject::class);
    }

    public function questions(): HasMany
    {
        return $this->hasMany(Question::class);
    }

    public function attempts(): HasMany
    {
        return $this->hasMany(ExamAttempt::class);
    }

    public function isActive(): bool
    {
        $now = now();
        return $this->status === 'published' 
            && $now->between($this->start_time, $this->end_time);
    }
}

Question Model

PHP
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class Question extends Model
{
    use HasFactory;

    protected $fillable = [
        'exam_id',
        'question_text',
        'question_type',
        'options',
        'correct_answer',
        'points',
        'order',
    ];

    protected $casts = [
        'options' => 'array',
    ];

    public function exam(): BelongsTo
    {
        return $this->belongsTo(Exam::class);
    }
}

Step 3: Run Migrations

BASH
php artisan migrate

Step 4: Create Seeders

BASH
php artisan make:seeder SubjectSeeder
PHP
<?php

namespace Database\Seeders;

use App\Models\Subject;
use App\Models\User;
use Illuminate\Database\Seeder;

class SubjectSeeder extends Seeder
{
    public function run(): void
    {
        $teacher = User::first();

        $subjects = [
            ['name' => 'Mathematics', 'code' => 'MATH101'],
            ['name' => 'Physics', 'code' => 'PHYS101'],
            ['name' => 'English', 'code' => 'ENG101'],
            ['name' => 'Computer Science', 'code' => 'CS101'],
        ];

        foreach ($subjects as $subject) {
            Subject::create([
                ...$subject,
                'teacher_id' => $teacher->id,
            ]);
        }
    }
}

Summary

We've designed a complete database schema with:

  • ✅ Subjects managed by teachers
  • ✅ Exams with configurable settings
  • ✅ Questions in multiple formats
  • ✅ Student exam attempts and answers
  • ✅ Proper relationships and constraints

What's Next

In Part 4, we'll implement authentication and user roles:

  • Role-based access (Admin, Teacher, Student)
  • Separate Filament panels for each role
  • Permission management with Spatie

Continue to Part 4: Authentication & User Roles →

ShareLinkedInXWhatsApp

Written by Muhammad Fari Madyan

Senior Backend Engineer and co-founder of LampungDev. I write up what I build so others can learn from it.

Work with me
← part 2Setting Up Laravel 12 with Filament Admin Panelpart 4 →Authentication & User Roles

Muhammad Fari Madyan

Senior Backend Engineer building real-time, high-concurrency systems that hold up in production. Co-founder of LampungDev. Based in Bandar Lampung, Indonesia (UTC+7), working remote.

Work

Case studiesCahTixExam platform, 4 stacksOpen source

© 2026 Muhammad Fari Madyan

Designed and built by Muhammad Fari Madyan