PHP code example of spatie / laravel-morph-map-generator

1. Go to this page and download the library: Download spatie/laravel-morph-map-generator library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

spatie / laravel-morph-map-generator example snippets


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

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` 

use Illuminate\Database\Eloquent\Model;

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

php artisan morph-map:clear

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

Relation::enforceMorphMap([
    'post' => 'App\Models\Post',
    'video' => 'App\Models\Video',
]);
bash
php artisan vendor:publish --provider="Spatie\LaravelMorphMapGenerator\MorphMapGeneratorServiceProvider" --tag="config"