PHP

Implement Polymorphic Relationships for Flexible Associations

Learn how to use Laravel Eloquent's polymorphic relationships to associate a model with multiple other models on a single association, enhancing data structure flexibility.

// 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');
    }
}

// Usage example
$post = App\Models\Post::find(1);
$comment = $post->comments()->create(['body' => 'Great post!']);

$video = App\Models\Video::find(1);
$comment = $video->comments()->create(['body' => 'Amazing video!']);

$comment = App\Models\Comment::find(1);
echo "Comment for " . $comment->commentable->getMorphClass() . ": " . $comment->commentable->title . "
"; // Access the parent model (Post or Video)
How it works: This snippet demonstrates setting up and using polymorphic relationships in Eloquent. A `Comment` model can belong to multiple types of models (e.g., `Post`, `Video`) using a single `commentable` relationship. The `morphTo()` method on the `Comment` model defines the inverse, while `morphMany()` on `Post` and `Video` models defines the forward relationship. This allows for flexible and reusable association structures, eliminating the need for separate relationships for each parent type and simplifying database schema.

Need help integrating this into your project?

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

Hire DigitalCodeLabs