laravel-json-api / laravel

JSON:API for Laravel applications

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Customize top-level meta when fetching related resource

od3n opened this issue · comments

Given I have this path to get all trips for the vehicle vehicles/{{vehicle_id}}/trips

{
    "meta": {
        "count": 2
    },
    "jsonapi": {
        "version": "1.0"
    },
    "data": [
        {
            "type": "trips",
            "id": "1",
            "attributes": {
                "started_at": "2024-01-10T09:00:00.000000Z",
                "ended_at": "2024-01-10T10:00:00.000000Z",
                "distance_in_km": 50
            }
        },
        {
            "type": "trips",
            "id": "2",
            "attributes": {
                "started_at": "2024-01-10T11:00:00.000000Z",
                "ended_at": "2024-01-10T1:00:00.000000Z",
                "distance_in_km": 90
            }
        }
    ]
}

How to customize the top-level meta member of the response document to include the sum of distance_in_km?

My current solution is to use readRelated{Field} hook. Any better or other solution for this? TIA

   # VehicleController.php
    public function readRelatedTrips(Vehicle $vehicle, $trips, $query)
    {
        return DataResponse::make($trips)
            ->withMeta(
                [
                    'total_trips' => $trips->count(),
                    'total_distance_in_km' => $trips->sum('distance_in_km')
                ]
            );
    }

Hi! The controller hooks exist for exactly this purpose, so you're doing it correctly.

The only thing you need to adjust is you should be using a RelatedResponse class instead of DataResponse:
https://laraveljsonapi.io/docs/3.0/responses/#related-response

So your code should be:

return RelatedResponse::make($vehicle, 'trips', $trips)
    ->withQueryParameters($query)
    ->withMeta([]);