How to globally set the default date output in Laravel 5?

3

I remember well when I used Laravel 4 that it was possible to globally convert the formats of created_at and updated_at , to display in JSON responses or even to the {{ $model->created_at }} direct call.

I did the following:

# app/global.php

Carbon\Carbon::setToStringFormat('d/m/Y H:i');

So, every time I called the Response::json or Model::toJson() method, the dates were converted to the above format.

But now this has not happened. Generally, I use a method called getCreatedAtBrAttribute to get the dates with the formatting. I also went so far as to use MomentJs to convert those dates through Javascript.

But now I want a solution in Laravel itself.

Is there a way in Laravel 5 to make all dates have a default format when they are called as a string?

    
asked by anonymous 14.03.2017 / 17:09

2 answers

3

Overwrite method serializeDate() aggregated by trait Illuminate\Database\Eloquent\Concerns\HasAttributes in your models .

You can do this by extending your models from an abstract class AbstractModel that extends the class #

  •     
  • 14.03.2017 / 18:28
    1

    You can also set a mutator (as long as you are using the Date or DateTime types):

    protected $casts = [
        'created_at' => 'datetime:Y-m-d h:i:s',
    ];
    

    Take a look at this link , I do not know which version of laravel 5 you are using, but from of 5.6 this is already available

        
    30.08.2018 / 19:48