skip to Main Content

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


  1. Usually, to modify JSON you can create resource

    php artisan make:resource UserResource
    

    In the UserResource

    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'groups' => $this->groups->map(function ($group) {
                return [
                    'name' => $group->name,
                    'joined' => $group->pivot->created_at
                ];
            })
        ];
    }
    

    In Controller

    public function show($id) # in your method
    {
        $user = User::with('groups')->findOrFail($id);
        return new UserResource($user); # call the UserResource
    }
    
    Login or Signup to reply.
  2. You can use laravel getAttribute magic method and appends the name to the query.

    You can do like this on your model:

    protected $appends = ['joined'];
    
    
    public function getJoinedAttribute(): string
    {
        return $this->pivot->created_at
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search