Assignments Of Day 14 Laravel Relationships

Assignments Of Day 14 

Laravel Relationships

Assignment 1: One-to-Many Relationship (Post and Comment)

Problem:

Create a one-to-many relationship between the Post and Comment models. A Post can have many Comments, and each Comment belongs to one Post.

  • Define the Post and Comment models.
  • Create the necessary database migrations for the posts and comments tables.
  • Write code to fetch all comments for a specific post.
  • Write code to find the post for a specific comment.

Solution:

1.  Create the Models and Migrations:

Run the following Artisan commands to create models and migrations:

bash

Copy code

php artisan make:model Post -m

php artisan make:model Comment -m

2.  Define the Models:

Post.php (Model)

php

Copy code

class Post extends Model

{

    public function comments()

    {

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

    }

}

Comment.php (Model)

php

Copy code

class Comment extends Model

{

    public function post()

    {

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

    }

}

3.  Create the Migrations:

In the create_posts_table migration, define the posts table:

php

Copy code

public function up()

{

    Schema::create('posts', function (Blueprint $table) {

        $table->id();

        $table->string('title');

        $table->text('content');

        $table->timestamps();

    });

}

In the create_comments_table migration, define the comments table:

php

Copy code

public function up()

{

    Schema::create('comments', function (Blueprint $table) {

        $table->id();

        $table->foreignId('post_id')->constrained()->onDelete('cascade');

        $table->text('comment');

        $table->timestamps();

    });

}

After defining the migrations, run the migration command:

bash

Copy code

php artisan migrate

4.  Fetch Comments for a Post:

In a controller or route, fetch all comments for a post:

php

Copy code

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

$comments = $post->comments; // Get all comments for this post

5.  Find the Post for a Comment:

To find the post associated with a specific comment:

php

Copy code

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

$post = $comment->post; // Get the post for this comment


Assignment 2: Many-to-Many Relationship (Student and Course)

Problem:

Create a many-to-many relationship between the Student and Course models. A Student can enroll in many Courses, and each Course can have many Students.

  • Define the Student and Course models.
  • Create the necessary database migrations for the students, courses, and pivot course_student tables.
  • Write code to fetch all courses for a student.
  • Write code to fetch all students enrolled in a course.

Solution:

1.  Create the Models and Migrations:

Run the following Artisan commands to create models and migrations:

bash

Copy code

php artisan make:model Student -m

php artisan make:model Course -m

2.  Define the Models:

Student.php (Model)

php

Copy code

class Student extends Model

{

    public function courses()

    {

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

    }

}

Course.php (Model)

php

Copy code

class Course extends Model

{

    public function students()

    {

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

    }

}

3.  Create the Migrations:

In the create_students_table migration, define the students table:

php

Copy code

public function up()

{

    Schema::create('students', function (Blueprint $table) {

        $table->id();

        $table->string('name');

        $table->timestamps();

    });

}

In the create_courses_table migration, define the courses table:

php

Copy code

public function up()

{

    Schema::create('courses', function (Blueprint $table) {

        $table->id();

        $table->string('course_name');

        $table->timestamps();

    });

}

In the pivot migration create_course_student_table, define the course_student pivot table:

php

Copy code

public function up()

{

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

    });

}

After defining the migrations, run the migration command:

bash

Copy code

php artisan migrate

4.  Fetch Courses for a Student:

In a controller or route, fetch all courses for a student:

php

Copy code

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

$courses = $student->courses; // Get all courses for this student

5.  Fetch Students for a Course:

To find all students enrolled in a specific course:

php

Copy code

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

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


Assignment 3: Attaching and Detaching Relationships (Many-to-Many)

Problem:

Using the many-to-many relationship between Student and Course, implement the following features:

  • Attach a new course to a student.
  • Detach a course from a student.
  • Sync courses for a student (i.e., add or remove courses based on an array of course IDs).

Solution:

1.  Attaching a Course to a Student:

To attach a course to a student, use the attach() method:

php

Copy code

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

$student->courses()->attach($courseId); // Attach course with ID $courseId

2.  Detaching a Course from a Student:

To detach a course from a student, use the detach() method:

php

Copy code

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

$student->courses()->detach($courseId); // Detach course with ID $courseId

3.  Syncing Courses for a Student:

To sync courses for a student, use the sync() method. This will attach the courses and remove any courses that are not in the provided array:

php

Copy code

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

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


Assignment 4: One-to-Many Relationship (Author and Book)

Problem:

Create a one-to-many relationship between the Author and Book models. An Author can write many Books, but each Book is written by only one Author.

  • Define the Author and Book models.
  • Create the necessary database migrations for the authors and books tables.
  • Write code to fetch all books for a specific author.
  • Write code to find the author for a specific book.

Solution:

1.  Create the Models and Migrations:

Run the following Artisan commands to create models and migrations:

bash

Copy code

php artisan make:model Author -m

php artisan make:model Book -m

2.  Define the Models:

Author.php (Model)

php

Copy code

class Author extends Model

{

    public function books()

    {

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

    }

}

Book.php (Model)

php

Copy code

class Book extends Model

{

    public function author()

    {

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

    }

}

3.  Create the Migrations:

In the create_authors_table migration, define the authors table:

php

Copy code

public function up()

{

    Schema::create('authors', function (Blueprint $table) {

        $table->id();

        $table->string('name');

        $table->timestamps();

    });

}

In the create_books_table migration, define the books table:

php

Copy code

public function up()

{

    Schema::create('books', function (Blueprint $table) {

        $table->id();

        $table->foreignId('author_id')->constrained()->onDelete('cascade');

        $table->string('title');

        $table->timestamps();

    });

}

After defining the migrations, run the migration command:

bash

Copy code

php artisan migrate

4.  Fetch Books for an Author:

In a controller or route, fetch all books for a specific author:

php

Copy code

$author = Author::find(1); // Find author with ID 1

$books = $author->books; // Get all books written by this author

5.  Find the Author for a Book:

To find the author of a specific book:

php

Copy code

$book = Book::find(1); // Find book with ID 1

$author = $book->author; // Get the author of this book


These assignments should help students understand how to implement and work with one-to-many and many-to-many relationships in Laravel.

4o mini

You said:

more

ChatGPT said:

ChatGPT

Here are a few more assignments that delve deeper into Laravel Eloquent Relationships:


Assignment 5: One-to-Many Relationship with Additional Data (Order and OrderItem)

Problem:

Create a one-to-many relationship between the Order and OrderItem models. Each Order can contain many OrderItems, but each OrderItem belongs to a specific Order.

  • Add the necessary database migrations for the orders and order_items tables, where an OrderItem has a quantity and price.
  • Create the Order and OrderItem models and define the relationship.
  • Write code to fetch all order items for a specific order.
  • Write code to calculate the total price of an order by summing the price * quantity for all order items.

Solution:

1.  Create the Models and Migrations:

Run the following Artisan commands:

bash

Copy code

php artisan make:model Order -m

php artisan make:model OrderItem -m

2.  Define the Models:

Order.php (Model)

php

Copy code

class Order extends Model

{

    public function items()

    {

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

    }

 

    public function totalPrice()

    {

        return $this->items->sum(function ($item) {

            return $item->quantity * $item->price;

        });

    }

}

OrderItem.php (Model)

php

Copy code

class OrderItem extends Model

{

    public function order()

    {

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

    }

}

3.  Create the Migrations:

In the create_orders_table migration:

php

Copy code

public function up()

{

    Schema::create('orders', function (Blueprint $table) {

        $table->id();

        $table->string('order_number');

        $table->timestamps();

    });

}

In the create_order_items_table migration:

php

Copy code

public function up()

{

    Schema::create('order_items', function (Blueprint $table) {

        $table->id();

        $table->foreignId('order_id')->constrained()->onDelete('cascade');

        $table->string('product_name');

        $table->integer('quantity');

        $table->decimal('price', 8, 2);

        $table->timestamps();

    });

}

After defining the migrations, run:

bash

Copy code

php artisan migrate

4.  Fetch Items for an Order and Calculate Total Price:

To fetch items for an order and calculate the total price:

php

Copy code

$order = Order::find(1); // Find the order with ID 1

$orderItems = $order->items; // Get all order items for this order

 

$totalPrice = $order->totalPrice(); // Calculate the total price of the order


Assignment 6: Many-to-Many with Pivot Table (User and Role)

Problem:

Create a many-to-many relationship between the User and Role models. A User can have many Roles, and a Role can be assigned to many Users.

  • Define the User and Role models.
  • Create a pivot table role_user with additional fields like assigned_at to track when the role was assigned to the user.
  • Write code to fetch all roles for a specific user.
  • Write code to fetch all users who have a specific role.
  • Use the sync method to update roles for a user.

Solution:

1.  Create the Models and Migrations:

Run the following Artisan commands:

bash

Copy code

php artisan make:model User -m

php artisan make:model Role -m

2.  Define the Models:

User.php (Model)

php

Copy code

class User extends Model

{

    public function roles()

    {

        return $this->belongsToMany(Role::class)->withPivot('assigned_at');

    }

}

Role.php (Model)

php

Copy code

class Role extends Model

{

    public function users()

    {

        return $this->belongsToMany(User::class)->withPivot('assigned_at');

    }

}

3.  Create the Migrations:

In the create_users_table migration:

php

Copy code

public function up()

{

    Schema::create('users', function (Blueprint $table) {

        $table->id();

        $table->string('name');

        $table->string('email')->unique();

        $table->timestamps();

    });

}

In the create_roles_table migration:

php

Copy code

public function up()

{

    Schema::create('roles', function (Blueprint $table) {

        $table->id();

        $table->string('role_name');

        $table->timestamps();

    });

}

In the pivot migration create_role_user_table:

php

Copy code

public function up()

{

    Schema::create('role_user', function (Blueprint $table) {

        $table->id();

        $table->foreignId('user_id')->constrained()->onDelete('cascade');

        $table->foreignId('role_id')->constrained()->onDelete('cascade');

        $table->timestamp('assigned_at');

        $table->timestamps();

    });

}

Run the migrations:

bash

Copy code

php artisan migrate

4.  Fetch Roles for a User and Users for a Role:

To fetch roles for a user:

php

Copy code

$user = User::find(1); // Find user with ID 1

$roles = $user->roles; // Get all roles for this user

To fetch users for a role:

php

Copy code

$role = Role::find(1); // Find role with ID 1

$users = $role->users; // Get all users with this role

5.  Sync Roles for a User:

To sync roles for a user:

php

Copy code

$user = User::find(1); // Find user with ID 1

$user->roles()->sync([1, 2]); // Sync roles with IDs 1 and 2


Assignment 7: Eager Loading with Relationships

Problem:

Use Eager Loading to efficiently load the related models for a Post and its Comments. You need to retrieve all posts along with their associated comments in one database query.

  • Fetch all posts and load their associated comments using eager loading (with() method).
  • Display the posts with their comments.

Solution:

1.  Eager Loading Posts with Comments:

To eager load comments for all posts, use the with() method:

php

Copy code

$posts = Post::with('comments')->get();

2.  Display the Posts and Comments:

In your view or controller, loop through the posts and their comments:

php

Copy code

foreach ($posts as $post) {

    echo $post->title . "<br>";

 

    foreach ($post->comments as $comment) {

        echo "- " . $comment->comment . "<br>";

    }

}


Assignment 8: Polymorphic Relationship (Image and Post)

Problem:

Create a polymorphic relationship between Image and Post. An Image can belong to either a Post or any other model in the future (e.g., Product), making it a polymorphic relationship.

  • Create the Image model and migrations with a polymorphic relationship.
  • Add a Post model and a related images table.
  • Write code to associate an image with a post.

Solution:

1.  Create the Models and Migrations:

Run the following Artisan commands:

bash

Copy code

php artisan make:model Image -m

2.  Define the Models:

Post.php (Model)

php

Copy code

class Post extends Model

{

    public function images()

    {

        return $this->morphMany(Image::class, 'imageable');

    }

}

Image.php (Model)

php

Copy code

class Image extends Model

{

    public function imageable()

    {

        return $this->morphTo();

    }

}

3.  Create the Migrations:

In the create_images_table migration:

php

Copy code

public function up()

{

    Schema::create('images', function (Blueprint $table) {

        $table->id();

        $table->string('url');

        $table->morphs('imageable'); // Creates imageable_id and imageable_type

        $table->timestamps();

    });

}

Run the migrations:

bash

Copy code

php artisan migrate

4.  Associate an Image with a Post:

php

Copy code

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

$post->images()->create([

    'url' => 'http://example.com/image.jpg',

]);


These additional assignments will help students gain deeper knowledge of Eloquent relationships, including one-to-many, many-to-many, eager loading, and polymorphic relationships.

 

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