sebastiaanluca / laravel-auto-morph-map

THIS PACKAGE HAS BEEN DEPRECATED — Automatically alias and map the polymorphic types of Eloquent models.
https://sebastiaanluca.com
MIT License
54 stars 9 forks source link

Enhancement: Retrieve the morph for a given model #2

Closed benrowe closed 5 years ago

benrowe commented 5 years ago

Description

It would be nice if I could pass through a either the FQCN or the an object and retrieve the morph as a string.

app(Mapper::class)->getMorphForModel(\App\SomeModel::class)

and/or

app(Mapper::class)->getMorphForModelObject($modelInstance)

This would be handy in cases of handling events, etc where you need to filter the model by a specific relationship type.

sebastiaanluca commented 5 years ago

Since the package just simplifies the model name and uses the Eloquent Relation class internally, you should be able to use $model->getMorphClass() to get the registered alias.

In most projects I even use a trait to wrap that method and provide it as an attribute:

<?php

declare(strict_types=1);

namespace App\Models;

trait HasAType
{
    /**
     * @return string
     */
    public function getTypeAttribute() : string
    {
        return $this->getMorphClass();
    }
}

If you want to get it from a class name:

app(\App\Models\Model::class)->getMorphClass();

Can you check if that works?

benrowe commented 5 years ago

Cheers

fernandocoronatomf commented 5 years ago

Hey @sebastiaanluca

quick question... any idea of why this output is being generated?

app(\App\Media::class)->getMorphClass();

outputs "medium"

Is it the expected behaviour? I would expect 'media' to be returned...

sebastiaanluca commented 5 years ago

That would be due to the active naming scheme. See the config file:

/**
 * The naming scheme to use when determining the model's morph type
 * base value. Defaults to singular table name.
 */
'naming' => NamingSchemes::SINGULAR_TABLE_NAME,

So the mapper takes the table name and singularizes it using Laravel's helper. In effect, media (plural) becomes medium (singular). You can disable this by either defining the morph type for media manually or using another naming scheme.

fernandocoronatomf commented 5 years ago

Sorry @sebastiaanluca actually the behaviour is correct.

We just did not know "medium" was singular of "Media" lol...

Some other colleagues did not know that too so we were a bit confused...

Thanks