Skip to content

Getting Started

Morphism provides enhanced polymorphic relationship management for Laravel with strict type enforcement, automatic morphing, and cleaner configuration.

Terminal window
composer require cline/morphism
config/app.php
'providers' => [
Cline\Morphism\MorphismServiceProvider::class,
],
Terminal window
php artisan vendor:publish --tag=morphism-config
config/morphism.php
return [
'morphs' => [
'commentable' => [
App\Models\Post::class,
App\Models\Video::class,
App\Models\Article::class,
],
'taggable' => [
App\Models\Post::class,
App\Models\Product::class,
],
],
];
use App\Models\Comment;
use App\Models\Post;
// Create polymorphic relation
$post = Post::find(1);
$comment = new Comment(['body' => 'Great post!']);
$post->comments()->save($comment);
// Query polymorphic relation
$comments = Comment::where('commentable_type', Post::class)->get();
// Without Morphism, morph maps use full class names
// commentable_type = "App\Models\Post"
// This breaks if you rename/move classes
// Couples database to PHP namespaces
// With Morphism, morph maps use clean aliases
// commentable_type = "post"
// Rename/move classes freely
// Database stays clean
// Type enforcement prevents invalid relations