I’m using Laravel 10 (planning to switch to 11 soon) to expose an API. Below is a simplified version of the issue that I’m having.
I have a table with users and a table with groups, and I have a many-to-many relationship between them. The pivot table has a column created_at which basically comes down to the moment that the user joined the group. When a user is retrieved through the API, I’m fetching the related groups with the pivot. This results in a JSON that looks like this (omitting irrelevant parts)
{
'groups':[
{
'name': 'group A',
'pivot': {
'created_at': '2024-...'
}
},
...
]
}
However, I would prefer an output that looks like this:
{
'groups':[
{
'name': 'group A',
'joined': '2024-...'
},
...
]
}
What is the best way to achieve this? I could completely handcraft the JSON, but then I’m losing quite a lot. There are other endpoints that expose groups outside of the context of a user, and these should not be affected.
2
Answers
Usually, to modify JSON you can create resource
In the
UserResource
In Controller
You can use laravel getAttribute magic method and appends the name to the query.
You can do like this on your model: