1. Go to this page and download the library: Download moneo/laravel-morphmap 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/ */
moneo / laravel-morphmap example snippets
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\MorphToMany;
use Moneo\LaravelMorphMap\Database\Eloquent\Concerns\HasCustomMorphMap;
class Post extends Model
{
use HasCustomMorphMap;
public function __construct(array $attributes = [])
{
parent::__construct($attributes);
// Define custom morph types per related model.
// Key: related model class, Value: morph type alias
$this->customMorphMap = [
Category::class => 'post',
];
// Optional: override the default morph type for all other relationships.
// If not set, defaults to the fully qualified class name (static::class).
// $this->defaultMorphType = 'post';
}
/**
* Tags relationship — no custom mapping defined for Tag,
* so the default morph type (App\Models\Post) will be used.
*/
public function tags(): MorphToMany
{
return $this->morphToMany(Tag::class, 'taggable');
}
/**
* Categories relationship — custom mapping defined above,
* so 'post' will be stored as the morph type.
*/
public function categories(): MorphToMany
{
return $this->morphToMany(Category::class, 'categoryable');
}
}
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\MorphToMany;
use Moneo\LaravelMorphMap\Database\Eloquent\Concerns\HasCustomMorphMap;
class Category extends Model
{
use HasCustomMorphMap;
public function posts(): MorphToMany
{
return $this->morphedByMany(Post::class, 'categoryable');
}
public function videos(): MorphToMany
{
return $this->morphedByMany(Video::class, 'categoryable');
}
}
bash
composer analyse
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.