Home » Php » php – Laravel 5 global date accessor

php – Laravel 5 global date accessor

Posted by: admin July 12, 2020 Leave a comment

Questions:

I watched a few Laracast lessons and now I’m building my first Laravel project. I have a few Eloquent models with timestamps for created_at and updated_at.

For displaying the right date format Laravel has a very nice functionality: accessors. But in EVERY Eloquent model I now have 2 functions like this:

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

This way the date will be forced to show as d-m-Y H:i:s. The only problem is: I don’t want to do this for every Model I create..

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

How to&Answers:

First of all, you don’t need to provide accessor to change the date format. It’s enough to set the $dateFormat variable in your model, e.g.:

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

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

Secondly, if you don’t want to set the $dateFormat variable for all your models, set it there and make all your models extend that class:

class BaseModel extends Illuminate\Database\Eloquent\Model {
  protected $dateFormat = 'U';
}

class User extends BaseModel {
  ...
}

Answer:

I was looking for the same, but unfortunately couldn’t come up with a way to create a global accessor.

The “problem” with the dateFormat property, is that it is a mutator, not an accessor. And extending a base class doesn’t work for both the User model and other models because it extends Authenticatable, and not the Model directly.

Here’s what I did as the next best thing – I created a FormatsDates trait. With your methods:

trait FormatsDates
{
    protected $newDateFormat = 'd-m-Y 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 on any model I want. e.g. the User model:

class User extends Authenticatable
{
    use FormatsDates;
}

Maybe somebody finds this useful.