Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel : display personal format of timestamps fields

In my project I used this code to format timestamps fields

date('D m Y  H:i', strtotime($post->created_at))

But as I have many places and fields to display it's a bit boring, and if I need to change the format it won"t be easy to maintain.

I'd like to know if there is a way to decalre the output format

like image 234
Lolo Avatar asked Jan 11 '23 02:01

Lolo


1 Answers

You can create an accessor function in your Post model.

public function getCreatedAtAttribute($value)
{
    return date('D m Y H:i', strtotime($value));
}

This way, each time you'll call $post->created_at it will display the date returned by your accessor instead of the default value.

More info here : http://laravel.com/docs/eloquent#accessors-and-mutators

If you don't want this function in all your models your can create a BaseModel class and make your models extend this BaseModel class.

I also found an other solution:

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

You can use this line (in global.php for exemple) but it will change the date format in all the application.

like image 185
Needpoule Avatar answered Jan 29 '23 00:01

Needpoule