Lecture Notes Of Day 14: Laravel Relationships

 

Lecture Notes Of Day 14 

Laravel Relationships

Objective:

To understand and implement Eloquent relationships in Laravel.

Outcome:

By the end of this session, students will be able to use one-to-many and many-to-many relationships in Laravel Eloquent ORM.


Introduction to Eloquent Relationships

In Laravel, Eloquent ORM (Object-Relational Mapping) provides a simple and elegant way to define relationships between database tables. Eloquent relationships are defined using methods in the model classes. This allows you to easily retrieve related data from different tables, without having to manually write complex SQL queries.

There are several types of relationships in Eloquent, including:

1.  One-to-One

2.  One-to-Many

3.  Many-to-Many

4.  Has Many Through

5.  Polymorphic Relations

For today’s class, we will focus on One-to-Many and Many-to-Many relationships.


1. One-to-Many Relationship

A one-to-many relationship occurs when one record in a table is associated with multiple records in another table. For example, one Post can have many Comments, but each Comment belongs to only one Post.

Defining a One-to-Many Relationship

In Laravel, you define a one-to-many relationship using the hasMany() method in the "parent" model (e.g., Post), and the belongsTo() method in the "child" model (e.g., Comment).

Example:

Let’s say we have two models: Post and Comment. A Post can have many Comments, but each Comment belongs to a single Post.

1.  Post Model (Parent) In the Post model, we define the hasMany() method to indicate that a post has many comments.

php

Copy code

// Post.php (Model)

class Post extends Model

{

    public function comments()

    {

        return $this->hasMany(Comment::class);

    }

}

This tells Laravel that the Post model is related to the Comment model with a one-to-many relationship.

2.  Comment Model (Child) In the Comment model, we define the belongsTo() method to indicate that each comment belongs to one post.

php

Copy code

// Comment.php (Model)

class Comment extends Model

{

    public function post()

    {

        return $this->belongsTo(Post::class);

    }

}

The belongsTo() method tells Laravel that the Comment model is related to the Post model, and each comment has one associated post.

Accessing Data in One-to-Many Relationship

To access the comments of a post:

php

Copy code

$post = Post::find(1); // Find the post with ID 1

$comments = $post->comments; // Get all comments related to this post

To access the post for a specific comment:

php

Copy code

$comment = Comment::find(1); // Find the comment with ID 1

$post = $comment->post; // Get the post related to this comment


2. Many-to-Many Relationship

A many-to-many relationship occurs when multiple records in one table are associated with multiple records in another table. For example, a Student can be enrolled in many Courses, and each Course can have many Students.

Defining a Many-to-Many Relationship

In Laravel, many-to-many relationships are defined using the belongsToMany() method in both models. Additionally, you need to define a pivot table that will hold the foreign keys of both models.

Example:

Let’s say we have two models: Student and Course. A student can enroll in many courses, and each course can have many students.

1.  Student Model In the Student model, we define the belongsToMany() method to indicate that a student belongs to many courses.

php

Copy code

// Student.php (Model)

class Student extends Model

{

    public function courses()

    {

        return $this->belongsToMany(Course::class);

    }

}

2.  Course Model In the Course model, we define the belongsToMany() method to indicate that a course belongs to many students.

php

Copy code

// Course.php (Model)

class Course extends Model

{

    public function students()

    {

        return $this->belongsToMany(Student::class);

    }

}

3.  Pivot Table For the many-to-many relationship to work, you need a pivot table. The table should store the foreign keys of the two related tables (i.e., student_id and course_id). In this case, we’ll name the pivot table course_student.

The migration for the pivot table looks like this:

php

Copy code

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();

});

The constrained() method automatically references the related tables (i.e., students and courses).

Accessing Data in Many-to-Many Relationship

To access the courses of a student:

php

Copy code

$student = Student::find(1); // Find the student with ID 1

$courses = $student->courses; // Get all courses related to this student

To access the students in a specific course:

php

Copy code

$course = Course::find(1); // Find the course with ID 1

$students = $course->students; // Get all students enrolled in this course

Attaching and Detaching Data in Many-to-Many

You can attach or detach related models in a many-to-many relationship using the following methods:

1.  Attaching a course to a student:

php

Copy code

$student = Student::find(1);

$student->courses()->attach($courseId); // $courseId is the ID of the course to attach

2.  Detaching a course from a student:

php

Copy code

$student = Student::find(1);

$student->courses()->detach($courseId); // Remove the relationship between the student and the course

3.  Syncing courses: If you want to attach multiple courses and remove the existing ones:

php

Copy code

$student->courses()->sync([1, 2, 3]); // Sync student to courses with IDs 1, 2, and 3


Conclusion

By the end of this lesson, you should now be able to define and work with one-to-many and many-to-many relationships in Laravel. These relationships allow you to efficiently retrieve and manipulate related data in a way that follows the principles of relational database design.

You should now be able to:

  • Use hasMany() and belongsTo() to define one-to-many relationships.
  • Use belongsToMany() to define many-to-many relationships.
  • Work with pivot tables for many-to-many relationships.

Practice Exercises:

1.  Exercise 1: Create a User model and a Post model. Define a one-to-many relationship between the two, where a user can have many posts.

2.  Exercise 2: Create a Book and Author model. Define a many-to-many relationship where an author can write many books, and a book can have many authors.



Comments

Popular posts from this blog

MCQs Of Day CRUD 8 Operations with Eloquent

Lecture Notes Of Day 24: Laravel Policies

MCQs of Day 7 Eloquent ORM Basics