Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

SigalZ's avatar

Custom Polymorphic Types - error

Using Laravel 10.

I have these 3 tables:

roasted_beans: id, name, green_bean_id

blends: id, name

shop_usages: id, shopusageable_id, shopusageable_type, date_used, weight

From Laravel documentation:

For example, instead of using the model names as the "type", we may use simple strings such as post and video. By doing so, the polymorphic "type" column values in our database will remain valid even if the models are renamed:

use Illuminate\Database\Eloquent\Relations\Relation;
 
Relation::enforceMorphMap([
    'post' => 'App\Models\Post',
    'video' => 'App\Models\Video',
]);

You may call the enforceMorphMap method in the boot method of your App\Providers\AppServiceProvider class

I added these relationships in the models:

ShopUsage model:
public function shopusageable(): MorphTo
    {
        return $this->morphTo();
    }

Blend model:
public function shopUsages(): MorphMany
    {
        return $this->morphMany(ShopUsage::class, 'shopusageable');
    }

RoastedBean model:
public function shopUsages(): MorphMany
    {
        return $this->morphMany(ShopUsage::class, 'shopusageable');
    }

I added this code in App\Providers\AppServiceProvider class in the boot method:

Relation::enforceMorphMap([
            'roastedBean' => 'App\Models\RoastedBean',
            'Blend' => 'App\Models\Blend',
        ]);

When I try to run a page on the site I get this error:

No morph map defined for model [App\Models\User].

What's the connection to User model? and it looks like it gets the error on this code line on the page:

@can('warehouse dashboard')

Which is on a menu checking if the user has the warehouse dashboard permission.

I don't understand what is going on.

0 likes
2 replies
SigalZ's avatar
SigalZ
OP
Best Answer
Level 5

I found the problem and giving the answer here in case someone else struggles with this.

It happened because I am using spatie/permissions and they also have a morph relationship.

I added the User model to App\Providers\AppServiceProvider as well, and now there's no error:

Relation::enforceMorphMap([
            'roastedBean' => 'App\Models\RoastedBean',
            'Blend' => 'App\Models\Blend',
			'User' => 'App\Models\User' //Added this
        ]);

Please or to participate in this conversation.