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

更新Laravel后出现Call to a member function setTimezone() on string错误如何解决?

解决Laravel更新后setTimezone()调用报错问题

错误提示「Call to a member function setTimezone() on string」说明$sale->order_time当前是字符串类型,而非Carbon日期实例——Laravel版本更新后,模型日期字段的自动转换规则发生了变化,导致该字段未被解析为Carbon对象。

以下是具体解决方法:

  • 检查并修正模型的日期字段配置
    旧版Laravel常用$dates属性指定需转换为Carbon的字段,新版更推荐使用$casts配置。在Sale模型中添加或修改对应配置:

    // 推荐方式:使用$casts
    protected $casts = [
        'order_time' => 'datetime',
    ];
    
    // 兼容旧版方式:使用$dates
    protected $dates = ['order_time'];
    

    若order_time存储的是Unix时间戳,需调整为'datetime:U'以匹配格式。

  • 手动转换为Carbon实例
    若暂时不想修改模型配置,可在Blade模板中手动将字符串转为Carbon对象后再调用方法:

    {{ \Carbon\Carbon::parse($sale->order_time)->setTimezone($venue->timezone) }}
    

    也可使用Laravel辅助函数简化:

    {{ now()->parse($sale->order_time)->setTimezone($venue->timezone) }}
    
  • 验证数据库字段类型
    确认数据库中order_time字段的类型为datetime或timestamp,而非varchar等字符串类型。字段类型错误会导致模型无法自动将其转换为Carbon实例。

内容的提问来源于stack exchange,提问作者Allfarid Morales García

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 14:20:58