Skip to content

A flaw in Relation::morphMap with inherited models #17830

@rickshawhobo

Description

@rickshawhobo
  • Laravel Version: 5.4
  • PHP Version: 7
  • Database Driver & Version: Mysql

Description:

The problem with morphMap is that you cannot extend a model and use the same map key.

Steps To Reproduce:

Let's say you have a User model with a polymorphic m-t-m relationship with Tags.

User Model looks like

... public function tags() { return $this->morphToMany(Tag::class, 'taggable'); } ... 

The morphMap looks like

'users' => 'App\Models\User' 

Now let's say you have a SpecialUser model that extends User. They both use the same table
and you want to use the same tags relationship.

This will not work

$specialUser = SpecialUser::find(1); $specialUser->tags(); 

Potential Solution:

Restore the deprecated protected $morphClass model member

 public function getMorphClass() { if ($this->morphClass !== null) { return $this->morphClass; } $morphMap = Relation::morphMap(); $class = static::class; if (! empty($morphMap) && in_array($class, $morphMap)) { return array_search($class, $morphMap, true); } return $class; } 

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions