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

Asked

Viewed 234 times

3

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

I’d do it this way:

# app/global.php

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

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

But now that hasn’t happened. Generally, I use a method called getCreatedAtBrAttribute to get the dates with the formatting. I also reached the extreme of using the MomentJs to convert these dates by Javascript.

But now I want a solution in Laravel himself.

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

  • 1

    I particularly put in $dates = ['data_inicio', 'data_fim']; and then add to $appends = ['data_format_br'].

  • @Diegosouza I also do this, but it is very tiring to do this in each model: I have some systems with 44 models :p

  • And if you put this function to convert the date to BR in the class that extends the Model ?

  • @Diegosouza I think it’s a great solution. I saw something similar here

  • This may help Wallace: https://laravel.com/docs/5.4/eloquent-mutators

2 answers

3


  • 2

    Boy, it was there in the bowels of the framework! Great!

1

you can set a mutator as well (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, do not know which version of Laravel 5 you are using, but from 5.6 this is already available

  • 1

    Oops, thanks for the info. Good to know that in new versions this problem is already solved better

Browser other questions tagged

You are not signed in. Login or sign up in order to post.