PHP
Defining and Querying Polymorphic Relationships in Eloquent
Learn how to implement polymorphic relationships in Laravel Eloquent, allowing a model to belong to multiple other models on a single association.
// app/Models/Comment.php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Comment extends Model
{
public function commentable()
{
return $this->morphTo();
}
}
// app/Models/Post.php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
public function comments()
{
return $this->morphMany(Comment::class, 'commentable');
}
}
// app/Models/Video.php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Video extends Model
{
public function comments()
{
return $this->morphMany(Comment::class, 'commentable');
}
}
// Example Usage
$post = App\Models\Post::find(1);
foreach ($post->comments as $comment) {
echo $comment->content;
}
$video = App\Models\Video::find(1);
foreach ($video->comments as $comment) {
echo $comment->content;
}
$comment = App\Models\Comment::find(1);
echo $comment->commentable->title; // Accesses title of Post or Video
How it works: Polymorphic relationships allow a 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. The `morphTo` method defines the inverse of the relationship, while `morphMany` or `morphOne` defines the relationship on the "parent" models. This pattern reduces database complexity and code duplication, making your application more flexible.