makapaka's avatar

Add count meta to json response

I would like to add a total count records to the json response of my API. I understand that it can be done using a Resource and pagination, however its kind of annoying that I would need to specify each field that needs to be returned.

Is there a faster way to just add the meta with total, without pagination - which I guess would have to subsequently wrap the data in data tag, or do I have to do it that way ?

Thx

0 likes
2 replies
bobbybouwmann's avatar
Level 88

Well you return your own json response in any controller, so you don't need to use a Resource! However a resources is a good practise for this kind of stuff ;)

Here's an example

public function index()
{
    $posts = Post::all();

    return response()->json([
        'posts' => $posts,
        'count' => $posts-count(),
    ]);
}

You can even decide to put posts into its own data key, but that's up to you ;)

makapaka's avatar

ah not sure where my brain is - so obvious, thanks!

Please or to participate in this conversation.