Search code examples
laraveleloquentpolymorphismlaravel-5.3

Eloquent ORM Polymorphic relationship


I'm trying to build a role-based user management but segmented by resource of many types.

I have this relational model: Relational model with basic tables

I need to show in the user profile management view something like this: Expected result view

But I don't want to make queries like:

RoleUser::where('user_id',1)->get();

I would like to use the many-to-many polymorphic relationship to take advantage of the Eager/Lazy loading of Laravel, but I don't know to do it. An other interesting feature to take into account, is that I don't want to store in the database the types like App\Models\Event, App\Models\Article or App\Models\Photo but the map is not working well for me (because the relationships aren't set properly).

//AppServiceProvider::boot()
Relation::morphMap([
    'event' => Event::class,
    'race'  => Race::class,
]);

Any idea?


Solution

  • Try this

        //AppServiceProvider::boot()
        Relation::morphMap([
            'event' => App\Models\Event::class,
            'race'  => App\Models\Race::class,
        ]);