laravel-json-api / laravel

JSON:API for Laravel applications
MIT License
551 stars 42 forks source link

[Feature request] Option to add count by default #196

Closed sneakylenny closed 2 years ago

sneakylenny commented 2 years ago

It would be nice to have the ability to return the count in the response without the client having to query for it specifically. The feature would look like this:

// HasMany::make('comments')->canCount();
HasMany::make('comments')->withCount();

So instead of having to query like this

GET /api/v1/posts/1?withCount=comments HTTP/1.1
Accept: application/vnd.api+json

I would be able to do just this

GET /api/v1/posts/1 HTTP/1.1
Accept: application/vnd.api+json

But still receive the same response:


{
  "data": {
    "type": "posts",
    "id": "1",
    "attributes": {
      "content": "...",
      "title": "Hello World"
    },
    "relationships": {
      "comments": {
        "links": {
          "self": "http://localhost/api/v1/posts/1/relationships/comments",
          "related": "http://localhost/api/v1/posts/1/comments"
        },
        "meta": {
          "count": 17
        }
      }
    },
    "links": {
      "self": "http://localhost/api/v1/posts/1"
    }
  }
}

It would make my client code cleaner since I need the relation count in most cases.

If this is already possible, help me out by referring to the docs. Maybe I missed it :p

steven-fox commented 2 years ago

The closest thing I'm seeing that's already available to you is HasMany::make('relation')->canCount()->alwaysCountInRelationship(). However, this only results in the meta.count attribute appearing in responses when:

  1. Specifically asking for it like normal via ...?withCount=relation
  2. Hitting the relationship route (.../posts/1/relationships/comments)
  3. Hitting the related route (.../posts/1/comments)

I recognize this isn't what you want (you wish to hit the show route for a specific post without the ?withCount query param but still receive the relation count), but perhaps you can review the laravel-json-api/eloquent package to see if you can implement this feature and submit a pull request for it!

sneakylenny commented 2 years ago

I don't have time for this at the moment. May reopen in the future.