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

后端 未结 4 1409
南方客
南方客 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:29

    Expanding on umbrel's answer a bit I've created a trait that turns the DateTimeInstance into a Carbon instance so that I can easily make use of it's common formats.

    In my particular case I wanted to serialize all dates according to ISO-8601.

    The trait is as follows...

    use DateTimeInterface;
    use Carbon\Carbon;
    
    trait Iso8601Serialization
    {
        /**
         * Prepare a date for array / JSON serialization.
         *
         * @param  \DateTimeInterface  $date
         * @return string
         */
        protected function serializeDate(DateTimeInterface $date)
        {
            return Carbon::instance($date)->toIso8601String();
        }
    
    }
    

    and from here I can simply use it on the relevant models...

    class ApiObject extends Model
    {
        use Iso8601Serialization;
    }
    

    Obviously you could name the trait more appropriately if you're using a different format but the point is that you can use any of Carbon's common formats simply by replacing toIso8601String() with the format you need.

提交回复
热议问题