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

Laravel时区适配教练时段API响应格式修正需求

Laravel教练可用时段API修正方案

核心需求回顾

需要返回标准化响应:

  • 包含教练user_id、name
  • 按星期分组的1小时时间槽,格式为HH:MM:SS
  • 时间需转换为指定时区(注:你提到的UST应为笔误,以下示例以UTC为例,支持任意合法时区)

1. 控制器逻辑修正

假设你的教练模型为Coach,可用时段关联模型为CoachAvailability,修正后的控制器方法如下:

use App\Models\Coach;
use Carbon\Carbon;
use Illuminate\Http\Request;

class CoachAvailabilityController extends Controller
{
    public function getAvailableSlots(Request $request)
    {
        // 验证请求参数合法性
        $request->validate([
            'timezone' => 'required|timezone',
            'coach_id' => 'required|exists:coaches,id'
        ]);

        $targetTimezone = $request->input('timezone');
        $coach = Coach::findOrFail($request->input('coach_id'));

        // 获取教练所有可用时段(假设数据库存储UTC标准时间)
        $rawSlots = $coach->availability()->get(['start_time', 'day_of_week']);

        // 处理时区转换、格式整理并按星期分组
        $formattedSlots = $this->getTimeSlot($rawSlots, $targetTimezone);

        // 返回标准化响应结构
        return response()->json([
            'user_id' => $coach->id,
            'name' => $coach->name,
            'available_slots' => $formattedSlots
        ]);
    }
}

2. 修正getTimeSlot方法

替换你现有的getTimeSlot方法,实现时区转换、格式适配与分组逻辑:

private function getTimeSlot($rawSlots, $targetTimezone)
{
    // 星期映射(可根据需求替换为中文或其他语言)
    $weekDayMap = [
        0 => 'Sunday',
        1 => 'Monday',
        2 => 'Tuesday',
        3 => 'Wednesday',
        4 => 'Thursday',
        5 => 'Friday',
        6 => 'Saturday'
    ];

    $groupedSlots = [];

    foreach ($rawSlots as $slot) {
        // 将数据库UTC时间转换为目标时区,并格式化为HH:MM:SS
        $convertedTime = Carbon::parse($slot->start_time, 'UTC')
            ->tz($targetTimezone)
            ->format('H:i:s');

        // 按星期分组
        $dayKey = $weekDayMap[$slot->day_of_week];
        if (!isset($groupedSlots[$dayKey])) {
            $groupedSlots[$dayKey] = [];
        }
        $groupedSlots[$dayKey][] = $convertedTime;
    }

    // 对每个星期的时间槽按时间排序
    foreach ($groupedSlots as &$slots) {
        sort($slots);
    }

    return $groupedSlots;
}

关键细节说明

  • 时区处理:依赖Carbon的tz()方法,将数据库存储的UTC标准时间转换为请求指定的目标时区(遵循后端存UTC、前端按需转时区的最佳实践)
  • 时间格式:通过format('H:i:s')强制输出HH:MM:SS格式的时间槽
  • 分组逻辑:基于数据库中day_of_week字段(建议存0-6代表周日到周六)映射为星期名称,也可直接用数字作为分组键
  • 响应结构:严格匹配需求,返回user_id、name及按星期分组的available_slots

示例响应

{
    "user_id": 1,
    "name": "John Doe",
    "available_slots": {
        "Monday": [
            "09:00:00",
            "14:00:00"
        ],
        "Wednesday": [
            "10:00:00",
            "16:00:00"
        ]
    }
}

内容的提问来源于stack exchange,提问作者Niraj Kumar Singh

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 03:20:43