Laravel One To Many Polymorphic Eloquent Relationship Tutorial Example

Laravel One To Many Polymorphic Eloquent Relationship Tutorial Example

In this tutorial, today we discuss about laravel many to many Eloquent relationship. Eloquent ORM means Object-relational Mapping and laravel provides a beautiful activerecord stucture. so we can easy to interact with application database. let’s start about One To Many Polymorphic eloquent relationship.

A one-to-many polymorphic relation is similar to a one to one eloquent relationship. but, the target model can belong to more than one type of model on a single association. For example, suppose we have posts and videos table. users can “comment” on both posts and videos.

here, see below database stucture.

posts

– id

– name

videos

– id

– name

comments

– id

– commentable_id

– commentable_type

Setting Database Configuration

After complete installation of laravel. we have to database configuration. now we will open the .env file and change the database name, username, password in the .env file. See below changes in a .env file.

Create Table using migration

Now, We need to create a migration. so we will below command using create the posts and images table migration.

After complete migration. we need below changes in the database/migrations/create_posts_table, database/migrations/create_videos_table and database/migrations/create_comments_table file.

create_posts_table.php

create_videos_table .php

create_comments_table .php

Run the below command. after the changes above file.

Create Model

Here below command help through we will create the Post, Video and Comment model. we will also use “morphMany()” function for Post and Video model.

Post.php

Video.php

Comment.php

Route and Controller

We have to need put below code route in routes/web.

Here below command help to create the post controller.

PostsController.php

Please follow and like us: