You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Laravel Resource API中自定义数据返回格式?

Hey there! Let's get that response format sorted to match exactly what you're looking for. Right now, the issue is twofold: your default BookingStatusResource is just returning raw date values, and using additional() is adding those room counts as top-level keys instead of pairing them with their corresponding dates. Here's how to fix it:

1. Customize Your BookingStatusResource

First, let's update the toArray() method to shape each item the way you need it—including formatting the date to your desired Y-m-d H:i:s format:

<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;
use Carbon\Carbon;

class BookingStatusResource extends JsonResource
{
    public function toArray($request)
    {
        return [
            'hasdate' => Carbon::parse($this->date)->format('Y-m-d H:i:s'),
            'hasroom' => $this->hasroom ?? 0, // Add a fallback in case of missing values
        ];
    }
}

2. Pair Dates and Room Counts in Your Controller

Instead of using additional(), we need to combine your dates and room counts into a single set of data where each date is linked to its corresponding room count. Then we'll pass this combined data to a resource collection (which automatically wraps everything in the data key for you):

// Assuming $hasdate is an array/collection of dates, and $hasroom is a matching array of room counts
$combinedData = collect($hasdate)->map(function ($date, $index) use ($hasroom) {
    return [
        'date' => $date,
        'hasroom' => $hasroom[$index] ?? 0,
    ];
});

// Return the collection of resources
return BookingStatusResource::collection($combinedData);

Why This Works:

  • We use collect()->map() to iterate over each date and pair it with the room count at the same index in $hasroom
  • The resource takes each paired item, formats the date correctly, and outputs the two fields you need
  • Using Resource::collection() ensures the final response is wrapped in a data array with each entry containing both hasdate and hasroom

Final Result

You'll get exactly the response structure you're expecting:

{
  "data": [
    {
      "hasdate": "2019-03-31 19:30:00",
      "hasroom": 3
    },
    {
      "hasdate": "2019-02-21 12:20:00",
      "hasroom": 2
    }
  ]
}

内容的提问来源于stack exchange,提问作者Farshad

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 09:24:05