PHP
Implement Polymorphic Relationships
Learn how to set up and query polymorphic relationships in Laravel Eloquent, enabling models 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 = 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; // Access parent (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`. The `morphTo` method on the `Comment` model defines the polymorphic relation, while `morphMany` on `Post` and `Video` models specify that they can have many comments. Laravel handles the necessary `commentable_id` and `commentable_type` columns automatically.