# 🏗️ Project Architecture & Structure

Comprehensive documentation of the School Management System architecture and design.

---

## 📋 Table of Contents

1. [Overview](#-overview)
2. [Folder Structure](#-folder-structure)
3. [Database Relationships](#-database-relationships)
4. [Data Models](#-data-models)
5. [Controllers](#-controllers)
6. [Routes](#-routes)
7. [Views](#-views)
8. [Middleware](#-middleware)
9. [Data Flow](#-data-flow)

---

## 🌐 Overview

### Architectural Pattern
The project follows Laravel's **MVC (Model-View-Controller)** pattern:

```
User Request
    ↓
Routes (web.php)
    ↓
Middleware (auth, roles, etc.)
    ↓
Controller
    ↓
Model (Eloquent) ← → Database
    ↓
View (Blade)
    ↓
Response
```

### Technology Stack

```
┌─────────────────────────────────────┐
│         Frontend Layer              │
│  - Blade Templates                  │
│  - TailwindCSS                      │
│  - Alpine.js                        │
│  - Vite (Build Tool)                │
└─────────────────────────────────────┘
              ↕
┌─────────────────────────────────────┐
│      Application Layer              │
│  - Laravel 12.0 Framework           │
│  - Controllers                      │
│  - Middleware                       │
│  - Form Requests                    │
│  - Services (optional)              │
└─────────────────────────────────────┘
              ↕
┌─────────────────────────────────────┐
│         Data Layer                  │
│  - Eloquent ORM                     │
│  - Models                           │
│  - Repositories (optional)          │
└─────────────────────────────────────┘
              ↕
┌─────────────────────────────────────┐
│       Database Layer                │
│  - MySQL 8.x                        │
│  - Migrations                       │
│  - Seeders                          │
└─────────────────────────────────────┘
```

---

## 📁 Folder Structure

```
school_system/
│
├── app/                                # Application Core
│   ├── Http/
│   │   ├── Controllers/               # Controllers
│   │   │   ├── StudentController.php
│   │   │   ├── TeacherController.php
│   │   │   ├── GradeController.php
│   │   │   ├── SubjectController.php
│   │   │   ├── AttendanceController.php
│   │   │   ├── MarkController.php
│   │   │   ├── FeeController.php
│   │   │   ├── PaymentController.php
│   │   │   └── ... (other controllers)
│   │   │
│   │   ├── Middleware/                # Middleware
│   │   │   ├── EnsureUserHasRole.php
│   │   │   └── ... (custom middleware)
│   │   │
│   │   └── Requests/                  # Form Validation Requests
│   │       ├── StoreStudentRequest.php
│   │       ├── UpdateStudentRequest.php
│   │       └── ... (other requests)
│   │
│   ├── Models/                        # Eloquent Models
│   │   ├── User.php                  # Users
│   │   ├── Student.php               # Students
│   │   ├── Teacher.php               # Teachers
│   │   ├── Grade.php                 # Grades
│   │   ├── Subject.php               # Subjects
│   │   ├── Attendance.php            # Attendance
│   │   ├── Mark.php                  # Marks
│   │   ├── Fee.php                   # Fees
│   │   ├── Payment.php               # Payments
│   │   ├── Exam.php                  # Exams
│   │   ├── Assignment.php            # Assignments
│   │   ├── Book.php                  # Books
│   │   ├── Borrowing.php             # Borrowings
│   │   ├── ParentModel.php           # Parents
│   │   ├── Note.php                  # Notes
│   │   ├── Schedule.php              # Schedules
│   │   ├── Event.php                 # Events
│   │   └── Setting.php               # Settings
│   │
│   ├── Providers/                     # Service Providers
│   │   └── AppServiceProvider.php
│   │
│   └── View/                          # View Components
│       └── Components/
│
├── bootstrap/                         # Bootstrap Files
│   ├── app.php
│   └── cache/                        # Cache for optimization
│
├── config/                            # Configuration Files
│   ├── app.php
│   ├── database.php
│   ├── auth.php
│   ├── permission.php                # Spatie Permission
│   └── ... (other configs)
│
├── database/                          # Database Files
│   ├── migrations/                   # 27 Migration Files
│   │   ├── 0001_01_01_000000_create_users_table.php
│   │   ├── 2025_12_20_164718_create_permission_tables.php
│   │   ├── 2025_12_20_172912_create_grades_table.php
│   │   ├── 2025_12_20_173052_create_students_table.php
│   │   └── ... (other migrations)
│   │
│   ├── seeders/                      # Data Seeders
│   │   ├── DatabaseSeeder.php
│   │   ├── UserSeeder.php
│   │   └── ... (other seeders)
│   │
│   └── factories/                    # Model Factories
│       └── UserFactory.php
│
├── public/                            # Public Assets
│   ├── index.php                     # Entry Point
│   ├── build/                        # Compiled Assets (Vite)
│   └── storage/                      # Symbolic Link
│
├── resources/                         # Frontend Resources
│   ├── views/                        # Blade Templates
│   │   ├── layouts/
│   │   │   ├── app.blade.php        # Main Layout
│   │   │   ├── guest.blade.php      # Guest Layout
│   │   │   └── navigation.blade.php
│   │   │
│   │   ├── students/
│   │   │   ├── index.blade.php
│   │   │   ├── create.blade.php
│   │   │   ├── edit.blade.php
│   │   │   └── show.blade.php
│   │   │
│   │   ├── teachers/
│   │   ├── grades/
│   │   ├── subjects/
│   │   ├── marks/
│   │   ├── attendances/
│   │   ├── fees/
│   │   ├── payments/
│   │   └── ... (other views)
│   │
│   ├── css/
│   │   └── app.css                   # Main CSS
│   │
│   └── js/
│       └── app.js                    # Main JavaScript
│
├── routes/                            # Route Definitions
│   ├── web.php                       # Web Routes
│   ├── api.php                       # API Routes
│   └── console.php                   # Console Commands
│
├── storage/                           # Storage Files
│   ├── app/                          # Application Files
│   ├── framework/                    # Framework Files
│   │   ├── cache/
│   │   ├── sessions/
│   │   └── views/
│   └── logs/                         # Log Files
│       └── laravel.log
│
├── tests/                             # Tests
│   ├── Feature/                      # Feature Tests
│   └── Unit/                         # Unit Tests
│
├── vendor/                            # Composer Dependencies
│
├── node_modules/                      # NPM Dependencies
│
├── .env                               # Environment Variables
├── .env.example                       # Environment Template
├── .gitignore                         # Git Ignore Rules
├── artisan                            # Artisan CLI
├── composer.json                      # PHP Dependencies
├── package.json                       # JS Dependencies
├── phpunit.xml                        # PHPUnit Config
├── vite.config.js                     # Vite Config
├── tailwind.config.js                 # Tailwind Config
├── README.md                          # Project Documentation
├── DATABASE_SETUP.md                  # Setup Guide
├── CONTRIBUTING.md                    # Contribution Guide
├── CHANGELOG.md                       # Version History
├── FAQ.md                             # Frequently Asked Questions
├── ARCHITECTURE.md                    # This File
└── LICENSE                            # MIT License
```

---

## 🔗 Database Relationships

### Entity Relationship Diagram (ERD)

```
┌─────────────┐
│    users    │
└──────┬──────┘
       │ 1:1
       ├──────────────────┬──────────────────┐
       │                  │                  │
       ▼                  ▼                  ▼
┌─────────────┐    ┌─────────────┐   ┌──────────────┐
│  students   │    │  teachers   │   │parent_models │
└──────┬──────┘    └──────┬──────┘   └──────┬───────┘
       │                  │                  │
       │ N:1              │ 1:N              │ 1:N
       │                  │                  │
       ▼                  ▼                  │
┌─────────────┐    ┌─────────────┐          │
│   grades    │◄───┤  subjects   │          │
└──────┬──────┘    └──────┬──────┘          │
       │ 1:N              │ 1:N              │
       │                  │                  │
       ├──────────────────┼──────────────────┘
       │                  │
       ▼                  ▼
┌─────────────┐    ┌─────────────┐
│    fees     │    │   marks     │
└─────────────┘    └──────┬──────┘
                          │
                          │ N:1
                          ▼
                   ┌─────────────┐
                   │    exams    │
                   └─────────────┘

┌─────────────┐    ┌─────────────┐
│  students   │───▶│ attendances │
└─────────────┘    └─────────────┘
       │
       │ 1:N
       ▼
┌─────────────┐
│  payments   │
└─────────────┘

┌─────────────┐    ┌─────────────┐
│  students   │───▶│ borrowings  │
└─────────────┘    └──────┬──────┘
                          │ N:1
                          ▼
                   ┌─────────────┐
                   │    books    │
                   └─────────────┘
```

### Relationship Details

#### Users & Authentication
```php
User (1) ──┬─→ (1) Student
           ├─→ (1) Teacher
           └─→ (1) ParentModel
```

#### Academic Structure
```php
Grade (1) ─→ (N) Student
Grade (1) ─→ (N) Subject
Grade (1) ─→ (N) Fee
Grade (1) ─→ (N) Exam

Subject (N) ─→ (1) Teacher
Subject (1) ─→ (N) Mark
Subject (1) ─→ (N) Schedule
Subject (1) ─→ (N) Assignment
```

#### Student Services
```php
Student (N) ─→ (1) Grade
Student (N) ─→ (1) ParentModel
Student (1) ─→ (N) Attendance
Student (1) ─→ (N) Mark
Student (1) ─→ (N) Payment
Student (1) ─→ (N) Borrowing
Student (1) ─→ (N) Note
```

#### Exams & Marks
```php
Mark (N) ─→ (1) Student
Mark (N) ─→ (1) Subject
Mark (N) ─→ (0..1) Exam

Exam (N) ─→ (1) Subject
Exam (N) ─→ (1) Grade
```

#### Library
```php
Borrowing (N) ─→ (1) Student
Borrowing (N) ─→ (1) Book
```

---

## 📦 Data Models

### Model: User

```php
class User extends Authenticatable
{
    // Relationships
    public function student(): HasOne
    public function teacher(): HasOne
    public function parent(): HasOne
    
    // Spatie Permission
    use HasRoles;
}
```

### Model: Student

```php
class Student extends Model
{
    // Relationships
    public function user(): BelongsTo           // User account
    public function grade(): BelongsTo          // Grade/Class
    public function parent(): BelongsTo         // Parent/Guardian
    public function attendances(): HasMany      // Attendance records
    public function marks(): HasMany            // Grades
    public function payments(): HasMany         // Payments
    public function borrowings(): HasMany       // Book borrowings
    public function notes(): HasMany            // Notes
    
    // Accessors & Mutators
    public function getFullNameAttribute()
    public function getAgeAttribute()
}
```

### Model: Teacher

```php
class Teacher extends Model
{
    // Relationships
    public function user(): BelongsTo
    public function subjects(): HasMany
    public function assignments(): HasMany
}
```

### Model: Grade

```php
class Grade extends Model
{
    // Relationships
    public function students(): HasMany
    public function subjects(): HasMany
    public function fees(): HasMany
    public function exams(): HasMany
}
```

### Model: Subject

```php
class Subject extends Model
{
    // Relationships
    public function grade(): BelongsTo
    public function teacher(): BelongsTo
    public function marks(): HasMany
    public function schedules(): HasMany
    public function assignments(): HasMany
    public function exams(): HasMany
}
```

---

## 🎛️ Controllers

### Controller Organization

```php
app/Http/Controllers/
│
├── Auth/                      # Authentication Controllers (Breeze)
│   ├── LoginController.php
│   ├── RegisterController.php
│   └── ...
│
├── StudentController.php      # Student CRUD
├── TeacherController.php      # Teacher CRUD
├── GradeController.php        # Grade CRUD
├── SubjectController.php      # Subject CRUD
├── AttendanceController.php   # Attendance Management
├── MarkController.php         # Marks Management
├── ExamController.php         # Exam Management
├── FeeController.php          # Fee Management
├── PaymentController.php      # Payment Processing
├── BookController.php         # Library Books
├── BorrowingController.php    # Book Borrowing
├── AssignmentController.php   # Homework Management
├── EventController.php        # School Events
├── ScheduleController.php     # Class Schedules
└── DashboardController.php    # Dashboard
```

### Example: StudentController

```php
class StudentController extends Controller
{
    // Display student list
    public function index()
    {
        $students = Student::with('grade', 'parent')
            ->latest()
            ->paginate(20);
            
        return view('students.index', compact('students'));
    }
    
    // Add new student
    public function store(StoreStudentRequest $request)
    {
        $student = Student::create($request->validated());
        
        return redirect()->route('students.index')
            ->with('success', 'Student added successfully');
    }
    
    // ... other methods
}
```

---

## 🛣️ Routes

### Route Organization

```php
// routes/web.php

// Public Routes
Route::get('/', function () {
    return view('welcome');
});

// Guest Routes (Login, Register)
Route::middleware('guest')->group(function () {
    Route::get('/login', [LoginController::class, 'show']);
    Route::post('/login', [LoginController::class, 'login']);
});

// Authenticated Routes
Route::middleware(['auth'])->group(function () {
    
    // Dashboard
    Route::get('/dashboard', [DashboardController::class, 'index']);
    
    // Admin Only Routes
    Route::middleware(['role:admin'])->group(function () {
        Route::resource('students', StudentController::class);
        Route::resource('teachers', TeacherController::class);
        Route::resource('grades', GradeController::class);
        Route::resource('fees', FeeController::class);
    });
    
    // Teacher Routes
    Route::middleware(['role:teacher|admin'])->group(function () {
        Route::resource('attendances', AttendanceController::class);
        Route::resource('marks', MarkController::class);
        Route::resource('assignments', AssignmentController::class);
    });
    
    // Student/Parent Routes
    Route::middleware(['role:student|parent'])->group(function () {
        Route::get('/my-grades', [StudentController::class, 'myGrades']);
        Route::get('/my-attendance', [StudentController::class, 'myAttendance']);
    });
});
```

---

## 🖼️ Views

### Blade Template Organization

```
resources/views/
│
├── layouts/
│   ├── app.blade.php          # Main Layout
│   ├── guest.blade.php        # Guest Layout
│   └── navigation.blade.php   # Nav Component
│
├── components/                # Reusable Components
│   ├── alert.blade.php
│   ├── button.blade.php
│   ├── input.blade.php
│   └── ...
│
├── students/
│   ├── index.blade.php        # List Students
│   ├── create.blade.php       # Add Student Form
│   ├── edit.blade.php         # Edit Student Form
│   └── show.blade.php         # Student Details
│
├── teachers/
├── grades/
├── marks/
└── ... (other views)
```

### Example: Layout

```blade
{{-- layouts/app.blade.php --}}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{{ config('app.name') }}</title>
    @vite(['resources/css/app.css', 'resources/js/app.js'])
</head>
<body>
    @include('layouts.navigation')
    
    <main>
        @yield('content')
    </main>
</body>
</html>
```

---

## 🛡️ Middleware

### Used Middleware

```php
// app/Http/Kernel.php

protected $middlewareGroups = [
    'web' => [
        'auth',              // Authentication
        'verified',          // Email verification
        'role:admin',        // Role check (Spatie)
        'permission:edit',   // Permission check (Spatie)
    ],
];
```

---

## 🔄 Data Flow

### Example: Add New Student

```
1. User fills form (create.blade.php)
   ↓
2. POST /students
   ↓
3. Route → StudentController@store
   ↓
4. Middleware: auth, role:admin
   ↓
5. Form Request Validation (StoreStudentRequest)
   ↓
6. Controller creates Student model
   ↓
7. Eloquent → Database INSERT
   ↓
8. Redirect to /students with success message
   ↓
9. Display students.index with new student
```

---

## 📊 Design Patterns Used

### 1. MVC Pattern
- **Model**: Eloquent Models
- **View**: Blade Templates
- **Controller**: HTTP Controllers

### 2. Repository Pattern (Optional)
For larger projects, separate database logic:

```php
interface StudentRepositoryInterface
{
    public function all();
    public function find($id);
    public function create(array $data);
}

class StudentRepository implements StudentRepositoryInterface
{
    // Implementation
}
```

### 3. Service Pattern (Optional)
For complex business logic:

```php
class PaymentService
{
    public function processPayment(Student $student, float $amount)
    {
        // Complex business logic
    }
}
```

---

<p align="center">
  <strong>📚 For more details, see other project files</strong>
</p>
