Laravel / Model / Relation : Polymorphic
Polymorphic Relationship
-
STEP
Models
post model
namespace App\Models; 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'); } } Note morphMany() Video Model:
namespace App\Models; 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'); } } Note morphMany() Comment Model:
namespace App\Models; use Illuminate\Database\Eloquent\Model; class Comment extends Model { /** * Get all of the owning commentable models. */ public function commentable() { return $this->morphTo(); } } Note morphTo() Retrieve Records:
$post = Post::find(1); dd($post->comments); $video = Video::find(1); dd($video->comments); Create Records:
$post = Post::find(1); $comment = new Comment; $comment->body = "Hi ItSolutionStuff.com"; $post->comments()->save($comment); $video = Video::find(1); $comment = new Comment; $comment->body = "Hi ItSolutionStuff.com"; $video->comments()->save($comment);