This is the fifth blog post of Laravel relationship Model tutorial series. In this tutorial, we are going to learn how to implement One to Many Polymorphic relationship within our Laravel application. Imagine that, If we have posts and videos tables, both need to add comments system. Then you can manage in a single table for both tables by using this One to Many Polymorphic relationship.
Prerequisites
Laravel
To Continue with this tutorial, you should have installed Laravel in your pc. If you are still not installed Laravel in your machine you can configure it from here.
Setting up the Project
First you need to create a new laravel project by running below command in your terminal
Now we need to create Post, Video and Comment model. we will also use morphMany()" and "morphTo()" for relationship of both model.
Post Model:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
<?php namespace App; use Illuminate\Database\Eloquent\Model; class Post extends Model { /** * Get all of the post's comments. */ public function comments() { return $this->morphMany(Comment::class, 'commentable'); } }
Video Model:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
<?php namespace App; use Illuminate\Database\Eloquent\Model; class Video extends Model { /** * Get all of the post's comments. */ public function comments() { return $this->morphMany(Comment::class, 'commentable'); } }
Comment Model:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
<?php namespace App; use Illuminate\Database\Eloquent\Model; class Comment extends Model { /** * Get all of the owning commentable models. */ public function commentable() { return $this->morphTo(); } }
In this tutorial, we learn how to implement one to many polymorphic relationship within Laravel. If you have any issue regarding this tutorial, mention your issue in comment section or reach me through my E-mail.