scrolltotop

new Get your brand recommended by ChatGPT, Perplexity & AI search engines. Discover GEO.

new We help companies keep track of engineering health with monthly reports. Start your review today.

Laravel Custom Morph Map

Per-relationship morph maps for Laravel polymorphic relations.

Home Company Open Source Laravel Custom Morph Map
The Problem

Global Morph Maps Create Global Conflicts

Laravel's Relation::morphMap() is global. It applies the same type aliases to every polymorphic relationship in your application. The moment you integrate with a third-party system, a legacy database, or any setup that stores different type identifiers in different tables, you hit a wall with no clean workaround.

Imagine your taggables table uses fully qualified class names while your categoryables table uses short aliases like post and video. With Laravel's built-in morphMap, you can't serve both. You have to pick one and hack around the other.

The Solution

Add the HasCustomMorphMap trait to your model and define which type aliases to use for which relationships. Different polymorphic relations on the same model can now use different type identifiers with no global state conflicts, no workarounds, and no hacks.

The trait hooks into Laravel's initialization lifecycle automatically. When you call morphToMany() or morphedByMany(), it looks up the related model in your custom map and registers the correct alias. Everything else falls through to the default behavior.

GitHub stars License PHP version Latest version

Key Features

  • Per-relationship morph maps. Different aliases for different polymorphic relationships.
  • morphToMany & morphedByMany. Works with both standard and inverse relations.
  • Zero configuration. No service provider needed. Just use the trait.
  • Automatic initialization. Wires up on model construction via Laravel convention.
  • Optional default type. Override the default morph type for all other relationships.

Requirements

  • PHP 8.1+
  • Laravel 10.x, 11.x, or 12.x

Installation

composer require moneo/laravel-morphmap
View on GitHub
Partnership is at the core of what we do.

Unsure where to start?
Let’s figure it out together 👋

Contact Us