Search code examples
phplaravelapilaravel-api

Laravel return custom api resource


I am currently creating an API to display the count of documents by types.

This is my type table:

id name
1 abc
2 bcd
3 efd

And this is my documents tables:

id document_name type_id
1 abc 1
2 bcd 2
3 efd 3

I want to return my Resource like this:

'title' => 'Title',
'types' => [
    [
        'label' => 'abc',
        'total' => 1
    ],
    [
        'label' => 'bcd',
        'total' => 2
    ],
    [
        'label' => 'efd',
        'total' => 3
    ]
]

How can I create a custom resource with looping?


Solution

  • You could create a resource that works for a single object, then use resource collection for the types to loop over the documents.

    https://laravel.com/docs/8.x/eloquent-resources#resource-collections