1

I have a relation between two tables - Many To Many.

I use the sync() method to save the related models:

public function tags()
{
    return $this->belongsToMany('Tag')->withTimestamps();
}

And this way I can set the timestamp fields - created_at and updated_at, but how can I override the format of those dates.

I have overriden the format for models using the following:

protected function getDateFormat()
{
    return 'U';
}

But it doesn't seem to work when using sync(). All records in the table are saved with the default date format.

Ivanka Todorova
  • 9,964
  • 16
  • 66
  • 103
  • The timestamp in pivot tables? The entire point of pivot table is to act as a bridge between ids. They should never contain any columns, but ids. But if you really need to do this for some wicked reason, you can approach it like this: http://stackoverflow.com/questions/24441395/how-to-change-default-format-at-created-at-and-updated-at-value-laravel – Yang Nov 16 '15 at 12:17
  • @dave I just want to keep track on when posts change their tags, so that's one way to do it. I'm asking how to change the format of the date WHEN storing the values in the database. – Ivanka Todorova Nov 16 '15 at 12:20
  • 1
    After spending some time exploring internals of `Illuminate\Database\Eloquent\Relations\BelongsToMany` I see that the time format is hard-coded. As an alternative solution, you can let Laravel update timestamps the way it does, and then create a timestamp from that format. Why not? This will do what you want and you'll get a timestamp (just tested it and it works fine). – Yang Nov 16 '15 at 12:52
  • @dave that's what I found too. I guess I will not use `sync()` at this time, because all of the other fields are in unix timestamp and the database is big. We will need to convert all the timestamps that we have and that will take time. Will do it in the near future. Thanks for helping! – Ivanka Todorova Nov 18 '15 at 13:28

1 Answers1

0

Use Carbon to manage those data. Save it like it is, but define mutuator for the model. Shortly -> mutuator is getter for specific data that came from database (in active record -> model class). Timestamps are returned as Carbon instance so format is super easy. Mutuators do it behind the scenes. Can mutuate as dates as model properties (encryption, formatting, etc.). Laravel doc show how to do it.

Janko
  • 202
  • 2
  • 11