我正在尝试在约会时使用访问器突变器,但出现各种错误。
目前:
public function getCreatedAtAttribute($date)
{
return $date->diffForHumans();
}
但我得到:
Call to a member function diffForHumans() on string
我只想在创建日期上使用 Carbon 函数,但总是收到此错误。
有什么帮助吗?
我正在尝试在约会时使用访问器突变器,但出现各种错误。
目前:
public function getCreatedAtAttribute($date)
{
return $date->diffForHumans();
}
但我得到:
Call to a member function diffForHumans() on string
我只想在创建日期上使用 Carbon 函数,但总是收到此错误。
有什么帮助吗?
这应该可以解决问题:
public function getCreatedAtAttribute()
{
return $this->attributes['created_at']->diffForHumans();
}
无论如何,这样做你将无法获得原始价值。因此,我建议您为具有其他名称的属性创建一个 getter,例如:
public function getHumanCreatedAtAttribute()
{
return $this->created_at->diffForHumans();
}
然后将其用作
$mode->human_created_at;
在您的 中执行以下操作BaseModel
:
public function getDates()
{
return ['created_at', 'updated_at'];
}
这将确保字段将created_at
被updated_at
视为Carbon
对象。