Defining Relationships: Polymorphic Relations

Allow a model to belong to more than one other model on a single association.

Table Structure

Posts
    id - integer
    title - string
    body - text

videos
    id - integer
    title - string
    url - string

comments
    id - integer
    body - text
    commentable_id - integer
    commentable_type - string

Model Structure

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Comment extends Model
{
    /**
     * Get all of the owning commentable models.
     */
    public function commentable()
    {
        return $this->morphTo();
    }
}

class Post extends Model
{
    /**
     * Get all of the post's comments.
     */
    public function comments()
    {
        return $this->morphMany('App\Comment', 'commentable');
    }
}

class Video extends Model
{
    /**
     * Get all of the video's comments.
     */
    public function comments()
    {
        return $this->morphMany('App\Comment', 'commentable');
    }
}

Retrieving Polymorphic Relations

$post = App\Post::find(1);

foreach ($post->comments as $comment) {
    //
}
$comment = App\Comment::find(1);

$commentable = $comment->commentable;

Custom Polymorphic Types

Use Illuminate\Database\Eloquent\Relations\Relation;

Relation::morphMap([
    'posts' => 'App\Post',
    'videos' => 'App\Video',
]);

Defining Relationships: Polymorphic Relations — Structure map

Clickable & Draggable!

Defining Relationships: Polymorphic Relations — Related pages: