Laravel 5 Global Access Date

I watched a few Laracast lessons and now I am building my first Laravel project. I have several Eloquent timestamped models for created_at and updated_at.

To display the correct date format, Laravel has very nice functionality: accessors. But in EVERY Eloquent model I now have 2 functions:

public function getUpdatedAtAttribute($value) { return Carbon::parse($value)->format('dmY H:i:s'); } public function getCreatedAtAttribute($value) { return Carbon::parse($value)->format('dmY H:i:s'); } 

Thus, the date will be displayed as dmY H:i:s . The only problem: I do not want to do this for every model I create.

Is there a default Laravel method / convention that I can do globally, or should I just make some kind of MasterModel and extend it instead of Model ?

+5
source share
2 answers

First of all, you do not need to provide an accessory to change the date format. This is enough to set the $ dateFormat variable in your model, for example:

 class User extends Model { protected $dateFormat = 'U'; // this will give you a timestamp } 

You can learn more about the available formats here: http://php.net/manual/en/function.date.php

Secondly, if you do not want to set the $ dateFormat variable for all your models, set it there and make all your models an extension of this class:

 class BaseModel extends Illuminate\Database\Eloquent\Model { protected $dateFormat = 'U'; } class User extends BaseModel { ... } 
+5
source

I was looking for the same thing, but unfortunately I could not create a way to create global access.

The β€œproblem” with the dateFormat property is that it is a mutator, not an accessory. The extension of the base class does not work both for the user model and for other models, since it extends Authenticatable, and not the model directly.

Here's what I did as the next best - I created the FormatsDates . Using your methods:

 trait FormatsDates { protected $newDateFormat = 'dmY H:i:s'; public function getUpdatedAtAttribute($value) { return Carbon::parse($value)->format($this->newDateFormat); } public function getCreatedAtAttribute($value) { return Carbon::parse($value)->format($this->newDateFormat); } } 

Now I can use this trait for any model I want. e.g. User Model:

 class User extends Authenticatable { use FormatsDates; } 

Maybe someone will find this useful.

+5
source

All Articles