Blog Detail

25

Apr
Automatically Generate Morph Maps in Your Laravel App cover image

arrow_back Automatically Generate Morph Maps in Your Laravel App

Spatie has launched a new package called Laravel Morph Map Generator which can automatically generate morph maps in your Laravel application. 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 implement 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.

Installation

You can install this package via composer by running this command in the terminal:

composer require spatie/laravel-morph-map-generator

You can publish the config file with:

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

The above command will generate the config file.

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

For more details and source code, you can visit its complete documentation on Github.

Published at : 25-04-2022

Author : Rizwan Aslam
AUTHOR
Rizwan Aslam

I am a highly results-driven professional with 12+ years of collective experience in the grounds of web application development especially in laravel, native android application development in java, and desktop application development in the dot net framework. Now managing a team of expert developers at Codebrisk.

Launch your project

Launch project