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

Laravel模型Accessor中用多行箭头函数转换created_at为Jalali日期

在Laravel模型中为created_at字段添加Jalali日期格式的Accessor(多表达式场景)

你原来的箭头函数写法存在语法错误——多行逻辑需要用花括号包裹,并且显式返回结果。下面是几种可行的最优实现方案:

方案一:修正多行箭头函数写法

如果只是少量多行逻辑,可以直接在箭头函数里用花括号包裹代码块,明确返回最终值:

protected function createdAt(): Attribute
{
    return Attribute::make(
        get: fn (string $value) => {
            $vertaDate = Verta::instance($value);
            return $vertaDate->format('Y/m/d H:i:s');
        },
    );
}

方案二:链式调用简化代码

如果逻辑只是实例化Verta并格式化,可以省略中间变量,用链式调用让代码更简洁:

protected function createdAt(): Attribute
{
    return Attribute::make(
        get: fn (string $value) => Verta::instance($value)->format('Y/m/d H:i:s'),
    );
}

方案三:抽离逻辑到私有方法(推荐复杂场景)

如果后续需要扩展更多日期处理逻辑(比如时区调整、特殊格式判断),或者需要在多个Accessor中复用该逻辑,建议把格式化逻辑抽成私有方法,提升代码可读性和复用性:

protected function createdAt(): Attribute
{
    return Attribute::make(
        get: fn (string $value) => $this->formatDateToJalali($value),
    );
}

private function formatDateToJalali(string $date): string
{
    $vertaDate = Verta::instance($date);
    // 这里可以添加额外逻辑,比如:
    // $vertaDate->setTimezone('Asia/Tehran');
    return $vertaDate->format('Y/m/d H:i:s');
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 04:37:13