PHP
Implement Polymorphic Relationships in Eloquent
Model flexible 'morph to' relationships where a child model can belong to multiple parent models using Laravel Eloquent's polymorphic features.
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
// Comment Model (e.g., app/Models/Comment.php)
class Comment extends Model
{
public function commentable()
{
return $this->morphTo();
}
}
// Post Model (e.g., app/Models/Post.php)
class Post extends Model
{
public function comments()
{
return $this->morphMany(Comment::class, 'commentable');
}
}
// Video Model (e.g., app/Models/Video.php)
class Video extends Model
{
public function comments()
{
return $this->morphMany(Comment::class, 'commentable');
}
}
// Database Migration (for 'comments' table)
// php artisan make:migration create_comments_table
Schema::create('comments', function (Blueprint $table) {
$table->id();
$table->text('body');
$table->morphs('commentable'); // Adds commentable_id (INT) and commentable_type (VARCHAR)
$table->timestamps();
});
// Usage:
$post = Post::find(1);
$post->comments->each(function ($comment) { echo $comment->body; });
$video = Video::find(1);
$video->comments->each(function ($comment) { echo $comment->body; });
$comment = Comment::find(1);
$commentable = $comment->commentable; // Can be a Post or a Video instance
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. Eloquent handles this by adding two columns to the child table: `commentable_id` (the ID of the parent) and `commentable_type` (the class name of the parent model). This provides great flexibility for designing database structures where related models can vary in type, simplifying your schema.