The issue you're encountering is due to the way Laravel handles resource collections and their metadata. When you return a single resource collection, Laravel automatically includes the metadata. However, when you combine multiple resource collections into a single JSON response, Laravel doesn't automatically merge the metadata from each collection.
To solve this, you need to manually extract and include the metadata from each collection in your response. Here's how you can do it:
- Extract the data and metadata from each collection.
- Combine them into a single response.
Here's an example of how you can achieve this:
$branchCollection = new BranchCollection($branches);
$endpointCollection = new EndpointCollection($endpoints);
$networkCollection = new NetworkCollection($networks);
return response()->json([
'branches' => $branchCollection->resolve(),
'branches_meta' => $branchCollection->additional,
'endpoints' => $endpointCollection->resolve(),
'endpoints_meta' => $endpointCollection->additional,
'networks' => $networkCollection->resolve(),
'networks_meta' => $networkCollection->additional,
]);
In this example:
-
resolve()is used to get the data from the collection. -
additionalis used to get the metadata.
This way, you ensure that both the data and the metadata from each collection are included in your JSON response.
If you want to keep the metadata within the same key as the data, you can structure your response like this:
$branchCollection = new BranchCollection($branches);
$endpointCollection = new EndpointCollection($endpoints);
$networkCollection = new NetworkCollection($networks);
return response()->json([
'branches' => [
'data' => $branchCollection->resolve(),
'meta' => $branchCollection->additional,
],
'endpoints' => [
'data' => $endpointCollection->resolve(),
'meta' => $endpointCollection->additional,
],
'networks' => [
'data' => $networkCollection->resolve(),
'meta' => $networkCollection->additional,
],
]);
This approach keeps the metadata nested within the same key as the data, making it more organized and easier to access.
By manually handling the metadata, you ensure that all parts of your response include the necessary information.