1

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.

Community
  • 1
  • 1
user1262878
  • 67
  • 2
  • 9

1 Answers1

4

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;

Glad To Help
  • 5,299
  • 4
  • 38
  • 56
  • But does this return the formatted date when doing it like this `return User::all()`? – user1262878 Oct 03 '13 at 09:36
  • See my modified answer. I tried it with actual code and it works. Note that you will have to add the column to the $appends attribute. See docs at bottom: http://laravel.com/docs/eloquent#converting-to-arrays-or-json – Glad To Help Oct 03 '13 at 11:53
  • At the same time I updated my question with the same findings. – user1262878 Oct 03 '13 at 11:57