To achieve the expected output where the data attribute is replaced with a custom name like a_custom_name, you need to override the toArray method in your OrderCollection class. However, you also need to ensure that the structure of the response is modified correctly to remove the data wrapper.
Here's how you can do it:
- Override the
toArraymethod in theOrderCollectionclass to return the custom structure. - Ensure that the pagination information is also correctly formatted.
Here's the updated code for your OrderCollection class:
use Illuminate\Http\Resources\Json\ResourceCollection;
class OrderCollection extends ResourceCollection
{
public function toArray($request): array
{
return [
'a_custom_name' => $this->collection->map(function ($item) use ($request) {
return (new OrderResource($item))->toArray($request);
}),
];
}
// Remove some links from pagination
public function paginationInformation($request, $paginated, $default)
{
// Remove links attribute
unset($default['meta']['links']);
// Additional attribute
$default['meta']['server'] = "someServer";
return $default;
}
}
In this code:
- The
toArraymethod is overridden to return an array with the keya_custom_namecontaining the collection ofOrderResourceitems. - The
paginationInformationmethod is used to customize the pagination metadata, removing thelinksattribute and adding a customserverattribute.
Your OrderResource class remains the same:
use Illuminate\Http\Resources\Json\JsonResource;
class OrderResource extends JsonResource
{
public function toArray($request): array
{
return [
'id' => $this->uuid,
'attributes' => [
'status_id' => $this->status_id->name,
'updatedAt' => $this->updated_at,
],
'includes' => new MessageResourceCollection($this->whenLoaded('messages')),
];
}
}
Finally, in your controller, you can return the OrderCollection as usual:
use App\Http\Resources\OrderCollection;
use App\Models\Order;
public function index()
{
return new OrderCollection(Order::where('x', '=', 'x')->paginate());
}
With these changes, the output should match your expected structure:
{
"a_custom_name": [
{
// data of a single attribute
}
],
"links": {
// pagination links
},
"meta": {
// pagination meta
"server": "someServer"
}
}
This approach ensures that the data attribute is replaced with your custom name while maintaining the correct structure for the pagination information.