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

Laravel中如何查询判断门店当前是否处于营业状态

Laravel 门店营业状态判断实现

需求说明

数据库中store_open_time字段以varchar格式存储JSON字符串,示例结构如下:

{
  "monday": "10:00-18:00;empty-empty",
  "tuesday": "10:00-21:00;empty-empty",
  "wednesday": "10:00-21:00;empty-empty",
  "thursday": "10:00-21:00;empty-empty",
  "friday": "10:00-21:00;empty-empty",
  "saturday": "10:00-14:00;15:00-19:00",
  "sunday": "10:00-14:00;15:00-19:00"
}

需根据当前时间判断门店是否营业,返回布尔值(例:周一11点返回true,19点返回false)。原代码仅获取当日营业时间字符串,需修改为直接返回营业状态。

实现代码

$store = MasterStore::find($id);
if (!$store) {
    return $this->sendResponse('error', 'Store not found', null, 404);
}

$openTimeConfig = json_decode($store->store_open_time, true);
$today = strtolower(Carbon::now()->format('l'));

// 无当日营业时间配置,默认不营业
if (!isset($openTimeConfig[$today])) {
    return $this->sendResponse('success', 'Get data success', false, 200);
}

$todayTimeSlots = explode(';', $openTimeConfig[$today]);
$currentTime = Carbon::now()->format('H:i');
$isOpen = false;

foreach ($todayTimeSlots as $slot) {
    // 跳过无效空时段
    if ($slot === 'empty-empty') {
        continue;
    }
    
    list($startTime, $endTime) = explode('-', $slot);
    // 校验当前时间是否在该营业时段内
    if ($currentTime >= $startTime && $currentTime <= $endTime) {
        $isOpen = true;
        break;
    }
}

return $this->sendResponse('success', 'Get data success', $isOpen, 200);

关键逻辑说明

  • 先校验门店是否存在,避免空指针异常
  • 将JSON字符串转为关联数组,简化后续取值操作
  • 通过Carbon获取当前星期几的小写标识(如monday)
  • 拆分当日的多个营业时段,逐个校验当前时间是否在有效区间内
  • 忽略empty-empty这类无效时段配置
  • 只要有一个时段包含当前时间,立即标记为营业状态并终止循环

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 01:40:08