PHP
Implement Flexible Polymorphic Relationships with Eloquent
Discover how to use Laravel Eloquent's polymorphic relationships to associate a model with multiple other models on a single relationship definition.
// In App\Models\Comment.php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Comment extends Model
{
/**
* Get the parent commentable model (post or video).
*/
public function commentable()
{
return $this->morphTo();
}
}
// In App\Models\Post.php
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');
}
}
// In App\Models\Video.php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Video extends Model
{
/**
* Get all of the video's comments.
*/
public function comments()
{
return $this->morphMany(Comment::class, 'commentable');
}
}
// Usage
$post = App\Models\Post::find(1);
foreach ($post->comments as $comment) {
echo $comment->body;
}
$video = App\Models\Video::find(5);
foreach ($video->comments as $comment) {
echo $comment->body;
}
$comment = App\Models\Comment::find(10);
echo $comment->commentable->title; // Accesses the Post or Video model
How it works: Polymorphic relationships allow a single model to belong to more than one other model on a single association. For example, a `Comment` model might belong to either a `Post` or a `Video` model. Instead of defining separate relationships for each parent type, Eloquent's `morphTo()` (on the child model) and `morphMany()` (on the parent models) abstract this. This pattern reduces database table complexity and code duplication, making your application more flexible and scalable when dealing with models that can relate to various types of content.