How do I change the date format Laravel outputs to JSON?

后端 未结 4 1406
南方客
南方客 2020-12-17 19:24

I\'ve built an application in Laravel and eloquent returns dates in this format: 2015-04-17 00:00:00. I\'m sending one particular query to JSON so I can make a

4条回答
  •  情歌与酒
    2020-12-17 20:04

    I know it's an old question, but there is still no good answer to that. Changing protected $dateFormat will affect database, instead method serializeDate() must be overriden

    class MyModel extends Eloquent {
        protected function serializeDate(\DateTimeInterface $date) {
            return $date->getTimestamp();
        }
    }
    

    Or myself I chose to create trait

    trait UnixTimestampSerializable
    {
        protected function serializeDate(\DateTimeInterface $date)
        {
            return $date->getTimestamp();
        }
    }
    

    and then add

    class SomeClassWithDates extends Model {    
        use UnixTimestampSerializable;
    
        ...
    }
    

提交回复
热议问题