@nanodreams Have you checked the Many To Many (Polymorphic) ? https://laravel.com/docs/10.x/eloquent-relationships#many-to-many-polymorphic-relations
Laravel Eloquent Query to retrieve effective users (morph relationship)
Hi there,
Thanks for the help in advance. I have a database schema with User, Group and Profile. To assign permissions I created a pivot table called memberable and added a morph relationship as follow:
users
- id
- ...
groups
- id
- ...
group_user
- group_id
- user_id
profiles
- id
- ...
memberables
- id
- memberable_id
- memberable_type
- profile_id
So far so good.
- I have users that belongs to groups.
- I have users assigned to profiles.
- I have groups assigned to profiles.
Now, my doubt is how to create a relationship in laravel to retrieve the "effective" users or the "effective" profiles. For example:
User::first()->effectiveProfiles => I would like to retrieve the profies that are either assigned directly to the user via morph or profiles assigned to a group via morph where the user is part of.
I can initially create a effectiveProfiles method in User model as:
public function effectiveProfiles()
{
return Profile::whereHas("users", fn($users) => $users->whereId($this->id))
->orWhereHas("groups", fn($groups) => $groups->whereHas("users", => $users->whereId($this->id)));
}
But this will be a method rather than a relationship where I can't do eagler loading and all beauty of Eloquent.
Does anyone came up with a solution for this type of scenarios?
Please or to participate in this conversation.