I have a model that I want to return as json. I want to return the timestamps as well. The problem is that the timestamps is saved in the following format 2013-10-02 09:45:22 but i want it in a different format. I still want the original format in the database but when it is outputted as JSON i want 2013.10.02. I found that you can override getDateFormat() but it does seem to change the format used in the db to.
I can always loop through the data before it is returned but it seems like this kind of code belongs in the model.
Updated with answer:
This Add a custom attribute to a Laravel / Eloquent model on load? explains how this works.
class User extends Eloquent {
protected $appends = array('my_date');
public function getMyDateAttribute()
{
return date('Y.m.d',strtotime($this->attributes['created_at']));
}
}
The critical part is the protected variable $appends which ensures that the accessor is included when the object is converted either with toArray or to Json.
You can create an additional accessor like:
class User extends Eloquent {
protected $appends = array('my_date');
public function setMyDateAttribute($value)
{
return $this->attributes['my_date'] = $value;
}
public function getMyDateAttribute($value)
{
return date('Y-m-d', strtotime($this->attributes['created_at']) );
}
}
and then use it like User->my_date;