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

donkfather's avatar

many to many to many

Hello to all,

I have a big dilema. I have to entities that have a many to many relationship. But the pivot table has a many to many with another entity.

for example:

Users       Roles       user_role           Tags
#id         #id         #user_id            #id
                        #role_id
                        other data

The user_role has a many to many with tags. Have can I do this with Eloquent ? Should I create another Model for user_role ? If I do

$user->roles()->attach($role)

I need the that to return the id or somehow get the id and based on that I need to add tags to that relation.

0 likes
4 replies
bestmomo's avatar

You need a model for your pivot to manage the second relation.

And maybe something like that to get the pivot last inserted id :

$user->roles()->latest()->first()->pivot->id
donkfather's avatar

@bestmomo Thanks. And I have to create that object manually I guess, am I right ? something like :

$user->roles()->attach('3',[attr])
$role = UserRoles::find($user->roles()->latest()->first()->pivot->id)
$role->tag()->attach([1,2,3] 

? :)

How would i get the roles of a user and the tags on that role ? $user->roles()->with('tags') ?

bestmomo's avatar

@donkfather

I think you need in addition to manyToMany :

  • hasMany between User and UserRoles
  • belongsTo between UserRoles and Role So you can use nested eager loading, something like this :
$user->with('userRoles.role', 'userRoles.tags')

Not sure of all that... needs some tests...

donkfather's avatar

@bestmomo i'll look into it. Anyway it is more than I have now :) . I can't retrieve the tags but with a Model on the UserRoles pivot I managed to insert them correctly.

Please or to participate in this conversation.