PHPackages                             spatie/laravel-morph-map-generator - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. spatie/laravel-morph-map-generator

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

spatie/laravel-morph-map-generator
==================================

Automatically generate morph maps in your Laravel application

1.4.0(2mo ago)73464.9k↓13.7%111MITPHPPHP ^7.4|^8.0CI passing

Since Oct 29Pushed 2mo ago3 watchersCompare

[ Source](https://github.com/spatie/laravel-morph-map-generator)[ Packagist](https://packagist.org/packages/spatie/laravel-morph-map-generator)[ Docs](https://github.com/spatie/laravel-morph-map-generator)[ GitHub Sponsors](https://github.com/sponsors/spatie)[ Fund](https://spatie.be/open-source/support-us)[ RSS](/packages/spatie-laravel-morph-map-generator/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (10)Dependencies (18)Versions (18)Used By (1)

Automatically generate morph maps in your Laravel application
=============================================================

[](#automatically-generate-morph-maps-in-your-laravel-application)

[![Latest Version on Packagist](https://camo.githubusercontent.com/1f6353bd9cd79eca78567fa5b12732f0ae35d96ea18964cd98d828f1d2116bcb/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f7370617469652f6c61726176656c2d6d6f7270682d6d61702d67656e657261746f722e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/spatie/laravel-morph-map-generator)[![Tests](https://github.com/spatie/laravel-morph-map-generator/workflows/Tests/badge.svg)](https://github.com/spatie/laravel-morph-map-generator/workflows/Tests/badge.svg)[![Psalm](https://github.com/spatie/laravel-morph-map-generator/workflows/Psalm/badge.svg)](https://github.com/spatie/laravel-morph-map-generator/workflows/Psalm/badge.svg)[![Check & fix styling](https://github.com/spatie/laravel-morph-map-generator/workflows/Check%20&%20fix%20styling/badge.svg)](https://github.com/spatie/laravel-morph-map-generator/workflows/Check%20&%20fix%20styling/badge.svg)[![Total Downloads](https://camo.githubusercontent.com/0576462c1d9aceebd7aa6806046e6b8b37128ea783d3a76e3bfb289be0954d21/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f7370617469652f6c61726176656c2d6d6f7270682d6d61702d67656e657261746f722e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/spatie/laravel-morph-map-generator)

With this package, you shouldn't worry about forgetting to add models to your application's morph map. Each model will autoregister itself in the morph map. The only thing you should do is implementing the `getMorphClass` method on your models like this:

```
class Post extends Model
{
    public function getMorphClass(): string {
        return 'post';
    }
}
```

From now on, the `Post` model will be represented as `post` within your morph map.

Support us
----------

[](#support-us)

[![](https://camo.githubusercontent.com/bb6ea335062bf390981bb365aa4cc6791c85d3c89bd5157316e723a95cb0af30/68747470733a2f2f6769746875622d6164732e73332e65752d63656e7472616c2d312e616d617a6f6e6177732e636f6d2f6c61726176656c2d6d6f7270682d6d61702d67656e657261746f722e6a70673f743d31)](https://spatie.be/github-ad-click/laravel-morph-map-generator)

We invest many resources into creating [best in class open source packages](https://spatie.be/open-source). You can support us by [buying one of our paid products](https://spatie.be/open-source/support-us).

We highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using. You'll find our address on [our contact page](https://spatie.be/about-us). We publish all received postcards on [our virtual postcard wall](https://spatie.be/open-source/postcards).

Installation
------------

[](#installation)

You can install the package via composer:

```
composer require spatie/laravel-morph-map-generator
```

You can publish the config file with:

```
php artisan vendor:publish --provider="Spatie\LaravelMorphMapGenerator\MorphMapGeneratorServiceProvider" --tag="config"
```

This is the contents of the published config file:

```
return [
    /*
    * When enabled, morph maps will be automatically generated when the
    * application is booted.
    */

    'autogenerate' => true,

    /**
     * Change the base directory if the models don't reside in the default App namespace.
     *
     * For example, the base directory would become 'src' if:
     * - Application is in src/App
     * - Models are in src/Domain
     */

    'base_directory' => '/',

    /*
    * Within these paths, the package will search for models to be included
    * in the generated morph map.
    */

    'paths' => [
        app_path(),
    ],

    /*
    * Only models that extend from one of the base models defined here will
    * be included in the generated morph map.
    */

    'base_models' => [
        Illuminate\Database\Eloquent\Model::class,
    ],

    /*
    * When generating the morph map, these models will not be included.
    */

    'ignored_models' => [],

    /*
    * Morph maps can be cached, there's a `FilesystemMorphMapCacheDriver` which
    * stores the morph map as a file in a directory or you can also use the
    * Laravel built-in cache by using `LaravelMorphMapCacheDriver`.
    *
    * Both drivers have their own config:
    * - `FilesystemMorphMapCacheDriver` requires a `path` to store the file
    * - `LaravelMorphMapCacheDriver` requires a `key` for storage
    */

    'cache' => [
        'type' => Spatie\LaravelMorphMapGenerator\Cache\FilesystemMorphMapCacheDriver::class,
        'path' => storage_path('app/morph-map-generator'),
    ],
];
```

Usage
-----

[](#usage)

First, you have to implement `getMorphClass` for the models you want to include in your morph map. We suggest you create a new base model class in your application from which all your models extend. So you could throw an exception when `getMorphClass` was not yet implemented:

```
use Illuminate\Database\Eloquent\Model;

abstract class BaseModel extends Model
{
    public function getMorphClass()
    {
        throw new Exception('The model should implement `getMorphClass`');
    }
}
```

When a model is not implementing `getMorphClass`, it will throw an exception when building the generated morph map, making it possible to quickly find models that do not have a morph map entry.

When `autogenerate` is enabled in the `morph-map-generator` config file, the morph map in your application will be dynamically generated each time the application boots. This is great in development environments since each time your application boots, the morph map is regenerated. For performance reasons, you should cache the dynamically generated morph map by running the following command:

```
php artisan morph-map:cache
```

Removing a cached morph map can be done by running:

```
php artisan morph-map:clear
```

When using Laravel 11+, the morph map can also be cached by using Laravel's optimize commands: `optimize` and `optimize:clear`

### Using a custom resolver

[](#using-a-custom-resolver)

You can also determine morph class values programmatically by using a custom resolver. For example, you could use the following to automatically derive the value based on the singular form of the model's table name:

```
MorphMapGenerator::resolveUsing(fn ($model) => Str::singular($model->getTable()));
```

Be warned! When the output of the closure above is not stable then you'll manually need to update all the `morhp_type` columns within your database. Using something like the table name is a good idea since those do not change that often.

You may set the resolver in the `boot` method of one of your service providers.

### Models outside your path

[](#models-outside-your-path)

Some models like the default Laravel User model and models defined by packages will not be discovered by this package since it only searches for models within the app path and not the complete vendor directory. You can include these models in your morph map by using the default [morph map](https://laravel.com/docs/12.x/eloquent-relationships#custom-polymorphic-types) feature from Laravel:

```
Relation::enforceMorphMap([
    'post' => 'App\Models\Post',
    'video' => 'App\Models\Video',
]);
```

Testing
-------

[](#testing)

```
composer test
```

Changelog
---------

[](#changelog)

Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently.

Contributing
------------

[](#contributing)

Please see [CONTRIBUTING](https://github.com/spatie/.github/blob/main/CONTRIBUTING.md) for details.

Security Vulnerabilities
------------------------

[](#security-vulnerabilities)

Please review [our security policy](../../security/policy) on how to report security vulnerabilities.

Credits
-------

[](#credits)

- [Ruben Van Assche](https://github.com/rubenvanassche)
- [All Contributors](../../contributors)

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

###  Health Score

60

—

FairBetter than 99% of packages

Maintenance84

Actively maintained with recent releases

Popularity50

Moderate usage in the ecosystem

Community23

Small or concentrated contributor base

Maturity67

Established project with proven stability

 Bus Factor2

2 contributors hold 50%+ of commits

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~129 days

Recently: every ~258 days

Total

16

Last Release

82d ago

Major Versions

0.0.2 → 1.0.02020-10-30

PHP version history (2 changes)0.0.1PHP ^7.4

1.0.3PHP ^7.4|^8.0

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/7535935?v=4)[Spatie](/maintainers/spatie)[@spatie](https://github.com/spatie)

---

Top Contributors

[![rubenvanassche](https://avatars.githubusercontent.com/u/619804?v=4)](https://github.com/rubenvanassche "rubenvanassche (40 commits)")[![freekmurze](https://avatars.githubusercontent.com/u/483853?v=4)](https://github.com/freekmurze "freekmurze (17 commits)")[![erikn69](https://avatars.githubusercontent.com/u/4933954?v=4)](https://github.com/erikn69 "erikn69 (8 commits)")[![alexmanase](https://avatars.githubusercontent.com/u/10696975?v=4)](https://github.com/alexmanase "alexmanase (7 commits)")[![Nielsvanpach](https://avatars.githubusercontent.com/u/10651054?v=4)](https://github.com/Nielsvanpach "Nielsvanpach (6 commits)")[![AdrianMrn](https://avatars.githubusercontent.com/u/12762044?v=4)](https://github.com/AdrianMrn "AdrianMrn (4 commits)")[![misenhower](https://avatars.githubusercontent.com/u/1619746?v=4)](https://github.com/misenhower "misenhower (4 commits)")[![AlexVanderbist](https://avatars.githubusercontent.com/u/6287961?v=4)](https://github.com/AlexVanderbist "AlexVanderbist (2 commits)")[![laravel-shift](https://avatars.githubusercontent.com/u/15991828?v=4)](https://github.com/laravel-shift "laravel-shift (2 commits)")[![mikerockett](https://avatars.githubusercontent.com/u/4586280?v=4)](https://github.com/mikerockett "mikerockett (1 commits)")[![angeljqv](https://avatars.githubusercontent.com/u/79208641?v=4)](https://github.com/angeljqv "angeljqv (1 commits)")[![PaolaRuby](https://avatars.githubusercontent.com/u/79208489?v=4)](https://github.com/PaolaRuby "PaolaRuby (1 commits)")

---

Tags

laravelmorph-mapsphpspatiespatielaravel-morph-map-generator

###  Code Quality

TestsPHPUnit

Static AnalysisPsalm

Type Coverage Yes

### Embed Badge

![Health badge](/badges/spatie-laravel-morph-map-generator/health.svg)

```
[![Health](https://phpackages.com/badges/spatie-laravel-morph-map-generator/health.svg)](https://phpackages.com/packages/spatie-laravel-morph-map-generator)
```

###  Alternatives

[spatie/laravel-enum

Laravel Enum support

3655.4M31](/packages/spatie-laravel-enum)[spatie/laravel-data

Create unified resources and data transfer objects

1.8k28.9M627](/packages/spatie-laravel-data)[spatie/laravel-health

Monitor the health of a Laravel application

86910.0M83](/packages/spatie-laravel-health)[spatie/laravel-settings

Store your application settings

1.5k5.9M72](/packages/spatie-laravel-settings)[spatie/laravel-event-sourcing

The easiest way to get started with event sourcing in Laravel

9003.7M26](/packages/spatie-laravel-event-sourcing)[spatie/laravel-typescript-transformer

Transform your PHP structures to TypeScript types

3736.0M45](/packages/spatie-laravel-typescript-transformer)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
