2015-08-15 24 views
0

我想在我的日期使用一個訪問器變異函數,但得到各種各樣的錯誤。Laravel 5日期變異函數

目前:

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

,但我得到:

Call to a member function diffForHumans() on string 

我只是想使用在日創建的碳功能,但總是得到這個錯誤。

任何幫助?

+0

你不想使用PHP的日期函數? – aldrin27

+0

將created_at添加到模型的$ dates數組中 – zeratulmdq

回答

1

這應該做的伎倆:

public function getCreatedAtAttribute() 
{ 
    return $this->attributes['created_at']->diffForHumans(); 
} 

不管怎樣,這樣做,你會使其無法得到原始值。因此,我建議你只需創建一個getter與另一名稱的屬性,如:

public function getHumanCreatedAtAttribute() 
{ 
    return $this->created_at->diffForHumans(); 
} 

,然後用它作爲

$mode->human_created_at; 
0

做好以下您BaseModel

public function getDates() 
{ 
    return ['created_at', 'updated_at']; 
} 

這將確保created_atupdated_at字段將被視爲Carbon對象。