I have a API endpoint which should list all users who are members of an organisation. Users and Organisations is a many-to-many relationship.
When listing the users in the organisation, the role of the user in the organisation, which exists on the pivot table, should be in the output, whereas normally it's just the user's details. Pretty standard stuff.
I have a Transformer class which takes care of outputting data for the API, so I have a transformForPublic(UserInterface $user)
method which returns an array of data that can be returned as the response. This only uses the interface to the object, so getName()
, getLocation()
etc.
The problem is that the pivot data only exists on the user object after a query. So I could have a method on my UserInterface called getOrganisationRoleFromPivot()
which simply returns $this->pivot->role
in the Eloquent implementation, but that's shit and will easily break.
Obviously I could just call $user->pivot->role
when I'm transforming the collection that I know has the data available, but I want to keep the Eloquent stuff out of the app logic.
I could have a nicely abstracted getRoleInOrganisation(OrganisationInterface $org)
, but this will have to do a query like $this->organisations()->where('organisation_id', '=', $org->getId())->first()->pivot->role;
for every user in the collection which won't scale at all.
Does anyone have any advice for how I could accomplish this while keeping the nice model interface abstractions?
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community