Structure database:
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
How to create Custom Polymorphic Types in Laravel:
By default, Laravel will use the fully qualified class name to store the type of the related model. For instance, given the one-to-many example above where a Comment
may belong to a Post
or a Video
, the default commentable_type
would be either App\Models\Post
or App\Models\Video
, respectively. However, you may wish to decouple your database from your application's internal structure. In that case, you may define a "morph map" to instruct Eloquent to use a custom name for each model instead of the class name:
use Illuminate\Database\Eloquent\Relations\Relation;
Relation::morphMap([
'posts' => 'App\Models\Post',
'videos' => 'App\Models\Video',
]);
You may register the morphMap
in the boot
function of your AppServiceProvider
or create a separate service provider if you wish.
You may determine the morph alias of a given model at runtime using the getMorphClass
method. Conversely, you may determine the fully-qualified class name associated with a morph alias using the Relation::getMorphedModel
method:
use Illuminate\Database\Eloquent\Relations\Relation;
$alias = $post->getMorphClass();
$class = Relation::getMorphedModel($alias);