【问题标题】:Why might diffForHumans be ignored in the Laravel5.5 model accessor?为什么 diffForHumans 在 Laravel5.5 模型访问器中会被忽略?
【发布时间】:2025-12-27 09:35:10
【问题描述】:

我想为 created_at 字段定义一个访问器。我的代码是:

public function getCreatedAtAttribute($value) {
    return $value->diffForHumans();
}

它会引发 Call to a member function diffForHumans() on null 错误。

但是$task->created_at->diffForHumans(); 在视图中可以正常工作。

【问题讨论】:

  • 当我填写的时候它告诉我Call to a member function diffForHumans() on string
  • 请展示更多你的代码..比如模型/控制器有 $task 和模型/控制器你想添加 greCreateAtAttribute

标签: php laravel-5 timestamp


【解决方案1】:

您应该使用“Carbon”类并创建一个访问器方法并遵循以下代码。

public function getCreatedAtAttribute($value)
        {
            $carbonDate = new Carbon($value);
            return $carbonDate->diffForHumans();
        }

$datetime = Carbon::createFromDate(2015, 8, 25); // or 
$datetime of course
return $datetime->diffForHumans();

【讨论】: