📅 Week 15 - Day 3: Database Relationships

Wednesday | Duration: 3 hours | Connect Your Data! 🔗

🎯 Learning Objectives

🔗 Types of Relationships

Relationship Description Example
One-to-One One record relates to one other User → Profile
One-to-Many One record has many related User → Posts
Many-to-Many Multiple records relate to multiple Students ↔ Courses

1️⃣ One-to-One Relationship

Example: Each User has one Profile. Each Profile belongs to one User.

users table profiles table ┌────┬─────────┐ ┌────┬─────────┬────────────┐ │ id │ name │ │ id │ user_id │ bio │ ├────┼─────────┤ ├────┼─────────┼────────────┤ │ 1 │ Ahmad │ ←── │ 1 │ 1 │ Developer │ │ 2 │ Fatima │ ←── │ 2 │ 2 │ Designer │ └────┴─────────┘ └────┴─────────┴────────────┘

Step 1: Create Migrations

# Create users table (if not exists) php artisan make:migration create_users_table # Create profiles table php artisan make:migration create_profiles_table <?php // database/migrations/xxxx_create_profiles_table.php public function up(): void { Schema::create('profiles', function (Blueprint $table) { $table->id(); $table->foreignId('user_id')->constrained()->onDelete('cascade'); $table->text('bio')->nullable(); $table->string('avatar')->nullable(); $table->string('website')->nullable(); $table->timestamps(); }); } ?>

Step 2: Define Relationship in Models

<?php // app/Models/User.php class User extends Model { // User has one profile public function profile() { return $this->hasOne(Profile::class); } } // app/Models/Profile.php class Profile extends Model { protected $fillable = ['user_id', 'bio', 'avatar', 'website']; // Profile belongs to one user public function user() { return $this->belongsTo(User::class); } } ?>

Step 3: Access Related Data

<?php // Get user's profile $user = User::find(1); $profile = $user->profile; echo $profile->bio; // Get profile's user $profile = Profile::find(1); $user = $profile->user; echo $user->name; ?>

2️⃣ One-to-Many Relationship

Example: One User can have many Posts. Each Post belongs to one User.

users table posts table ┌────┬─────────┐ ┌────┬─────────┬──────────────┐ │ id │ name │ │ id │ user_id │ title │ ├────┼─────────┤ ├────┼─────────┼──────────────┤ │ 1 │ Ahmad │ ←── │ 1 │ 1 │ First Post │ │ │ │ ←── │ 2 │ 1 │ Second Post │ │ 2 │ Fatima │ ←── │ 3 │ 2 │ Fatima Post │ └────┴─────────┘ └────┴─────────┴──────────────┘

Step 1: Create Posts Migration

php artisan make:model Post -m <?php // database/migrations/xxxx_create_posts_table.php public function up(): void { Schema::create('posts', function (Blueprint $table) { $table->id(); $table->foreignId('user_id')->constrained()->onDelete('cascade'); $table->string('title'); $table->text('content'); $table->timestamps(); }); } ?>

Step 2: Define Relationships

<?php // app/Models/User.php class User extends Model { // User has many posts public function posts() { return $this->hasMany(Post::class); } } // app/Models/Post.php class Post extends Model { protected $fillable = ['user_id', 'title', 'content']; // Post belongs to one user public function user() { return $this->belongsTo(User::class); } } ?>

Step 3: Use the Relationship

<?php // Get all posts by a user $user = User::find(1); $posts = $user->posts; // Collection of Post models foreach ($posts as $post) { echo $post->title . "<br>"; } // Get post's author $post = Post::find(1); $author = $post->user; echo "Written by: " . $author->name; // Count user's posts $postCount = $user->posts()->count(); // Create post for user $user->posts()->create([ 'title' => 'New Post', 'content' => 'Post content here' ]); ?>

3️⃣ Many-to-Many Relationship

Example: Students can enroll in many Courses. Courses can have many Students.

students course_student (pivot) courses ┌────┬────────┐ ┌────┬────────────┬──────────┐ ┌────┬─────────────┐ │ id │ name │ │ id │ student_id │ course_id│ │ id │ name │ ├────┼────────┤ ├────┼────────────┼──────────┤ ├────┼─────────────┤ │ 1 │ Ahmad │ ←── │ 1 │ 1 │ 1 │ ──→ │ 1 │ Web Dev │ │ │ │ ←── │ 2 │ 1 │ 2 │ ──→ │ 2 │ Data Sci │ │ 2 │ Fatima │ ←── │ 3 │ 2 │ 1 │ │ 3 │ UI/UX │ │ │ │ ←── │ 4 │ 2 │ 3 │ ──→ └────┴─────────────┘ └────┴────────┘ └────┴────────────┴──────────┘

Step 1: Create Migrations

# Create students and courses tables php artisan make:model Student -m php artisan make:model Course -m # Create pivot table (alphabetical order: course_student) php artisan make:migration create_course_student_table <?php // database/migrations/xxxx_create_students_table.php public function up(): void { Schema::create('students', function (Blueprint $table) { $table->id(); $table->string('name'); $table->string('email')->unique(); $table->timestamps(); }); } // database/migrations/xxxx_create_courses_table.php public function up(): void { Schema::create('courses', function (Blueprint $table) { $table->id(); $table->string('name'); $table->text('description'); $table->timestamps(); }); } // database/migrations/xxxx_create_course_student_table.php public function up(): void { Schema::create('course_student', function (Blueprint $table) { $table->id(); $table->foreignId('student_id')->constrained()->onDelete('cascade'); $table->foreignId('course_id')->constrained()->onDelete('cascade'); $table->timestamps(); }); } ?>

Step 2: Define Relationships

<?php // app/Models/Student.php class Student extends Model { protected $fillable = ['name', 'email']; // Student belongs to many courses public function courses() { return $this->belongsToMany(Course::class); } } // app/Models/Course.php class Course extends Model { protected $fillable = ['name', 'description']; // Course belongs to many students public function students() { return $this->belongsToMany(Student::class); } } ?>

Step 3: Working with Many-to-Many

<?php // Get student's courses $student = Student::find(1); $courses = $student->courses; foreach ($courses as $course) { echo $course->name . "<br>"; } // Get course's students $course = Course::find(1); $students = $course->students; // Enroll student in course (attach) $student->courses()->attach($courseId); // Enroll in multiple courses $student->courses()->attach([1, 2, 3]); // Remove enrollment (detach) $student->courses()->detach($courseId); // Remove all enrollments $student->courses()->detach(); // Sync (replace all enrollments) $student->courses()->sync([1, 3, 5]); // Toggle enrollment $student->courses()->toggle($courseId); // Check if enrolled if ($student->courses()->where('course_id', 1)->exists()) { echo "Already enrolled!"; } ?>

💻 Complete Enrollment System Example

Controller:

<?php // app/Http/Controllers/EnrollmentController.php namespace App\Http\Controllers; use App\Models\Student; use App\Models\Course; use Illuminate\Http\Request; class EnrollmentController extends Controller { // Show enrollment form public function create() { $students = Student::all(); $courses = Course::all(); return view('enrollment.create', compact('students', 'courses')); } // Process enrollment public function store(Request $request) { $student = Student::find($request->student_id); // Check if already enrolled if ($student->courses()->where('course_id', $request->course_id)->exists()) { return back()->with('error', 'Already enrolled in this course!'); } // Enroll student $student->courses()->attach($request->course_id); return back()->with('success', 'Student enrolled successfully!'); } // Show student's courses public function show($studentId) { $student = Student::with('courses')->findOrFail($studentId); return view('enrollment.show', compact('student')); } // Unenroll public function destroy($studentId, $courseId) { $student = Student::findOrFail($studentId); $student->courses()->detach($courseId); return back()->with('success', 'Unenrolled successfully!'); } } ?>

Display Student's Courses:

<!-- resources/views/enrollment/show.blade.php --> <h1>{{ $student->name }}'s Courses</h1> @if($student->courses->count() > 0) <table> <tr> <th>Course Name</th> <th>Description</th> <th>Action</th> </tr> @foreach($student->courses as $course) <tr> <td>{{ $course->name }}</td> <td>{{ $course->description }}</td> <td> <form action="/enrollment/{{ $student->id }}/{{ $course->id }}" method="POST"> @csrf @method('DELETE') <button>Unenroll</button> </form> </td> </tr> @endforeach </table> @else <p>Not enrolled in any courses yet.</p> @endif

⚡ Eager Loading (Performance)

<?php // BAD: N+1 Query Problem $students = Student::all(); foreach ($students as $student) { echo $student->courses; // Separate query for EACH student! } // GOOD: Eager Loading (2 queries total) $students = Student::with('courses')->get(); foreach ($students as $student) { echo $student->courses; // Already loaded! } // Load multiple relationships $students = Student::with(['courses', 'profile'])->get(); ?>

✏️ Practice Exercises

  1. Create Author → Books (One-to-Many) relationship
  2. Implement Product → Reviews (One-to-Many)
  3. Build Tags ↔ Posts (Many-to-Many) system
  4. Create enrollment system for students and courses
  5. Display all courses with student count
  6. Show all students with their enrolled courses

✅ Today's Deliverable

← Previous Course Home Next Week →