PHP
Managing Diverse Related Models with Eloquent Polymorphic Relationships
Learn how to use Laravel Eloquent's polymorphic relationships to associate a model with multiple other models on a single association type, enhancing flexibility.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
public function comments()
{
return $this->morphMany(Comment::class, 'commentable');
}
}
class Video extends Model
{
public function comments()
{
return $this->morphMany(Comment::class, 'commentable');
}
}
class Comment extends Model
{
public function commentable()
{
return $this->morphTo();
}
}
// Example Usage:
$post = Post::find(1);
$post->comments()->create(['body' => 'Great post!']);
$video = Video::find(1);
$video->comments()->create(['body' => 'Awesome video!']);
$comment = Comment::find(1);
echo $comment->commentable->title; // Accessing the parent (Post or Video)
How it works: This snippet demonstrates Eloquent's polymorphic relationships, allowing a single model (like Comment) to belong to multiple other models (like Post or Video) using a single relationship definition. This is achieved by adding `commentable_id` and `commentable_type` columns to the `comments` table. The `morphMany` method is used on the parent models, and `morphTo` on the child model, making the relationship highly flexible.