PHP

Building Flexible Relationships with Eloquent Polymorphic Relations

Implement polymorphic relationships in Laravel Eloquent to allow a single model to belong to multiple types of other models, enhancing database flexibility.

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

// Define a Comment model that can belong to either Post or Video
class Comment extends Model
{
    protected $fillable = ['body', 'commentable_id', 'commentable_type'];

    public function commentable()
    {
        return $this->morphTo();
    }
}

// Define a Post model
class Post extends Model
{
    protected $fillable = ['title', 'content'];

    public function comments()
    {
        return $this->morphMany(Comment::class, 'commentable');
    }
}

// Define a Video model
class Video extends Model
{
    protected $fillable = ['title', 'url'];

    public function comments()
    {
        return $this->morphMany(Comment::class, 'commentable');
    }
}

// Usage:
$post = App\Models\Post::create(['title' => 'My First Post', 'content' => 'Lorem ipsum.']);
$commentPost = $post->comments()->create(['body' => 'Great post!']);

$video = App\Models\Video::create(['title' => 'Laravel Tutorial', 'url' => 'youtube.com/laravel']);
$commentVideo = $video->comments()->create(['body' => 'Awesome video!']);

// Retrieve comments and their parent
$retrievedCommentPost = App\Models\Comment::find($commentPost->id);
echo "Comment on '" . $retrievedCommentPost->commentable->title . "': " . $retrievedCommentPost->body . "
";

$retrievedCommentVideo = App\Models\Comment::find($commentVideo->id);
echo "Comment on '" . $retrievedCommentVideo->commentable->title . "': " . $retrievedCommentVideo->body . "
";

// With eager loading the polymorphic relation
$comments = App\Models\Comment::with('commentable')->get();
foreach ($comments as $comment) {
    echo "Comment (ID: {$comment->id}) on '" . $comment->commentable->title . "'.
";
}
How it works: Polymorphic relationships allow a model to belong to more than one other model on a single association. For instance, a `Comment` model might belong to either a `Post` or a `Video` model without duplicating foreign key columns for each possible parent. The `morphTo()` method defines the inverse of the polymorphic relationship, while `morphMany()` (or `morphOne()`) defines the one-to-many side. This pattern makes your database schema and model definitions more flexible, reducing redundancy and making it easier to add new commentable types in the future.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs