0

Can i have more than 1 getter for my attribute in my Model.

I have a date and i would like to have it in both variations as a date and as a human readable format with Carbon

Now if i make this:

convert the UTC to human readable format

public function getCreatedAtAttribute($date){

Carbon::setLocale('de');
return Carbon::createFromFormat('Y-m-d H:i:s', $date)->diffForHumans();

}

I get it in human readable.

How to get the normal date?

Balraj Allam
  • 611
  • 6
  • 24
lewis4u
  • 14,256
  • 18
  • 107
  • 148

1 Answers1

1

If you want to get human readable date and as well as normal date then you can add the created_at column in Model as

protected $dates = ['created_at'];

which gives us the carbon date instance and to get the human readable date you can do it as

$model_instance->created_at->diffForHumans();

ANSWER UPDATE

You can get the createdAt date in different formats by adding the custom accessors:

class ModelName extends Model {
     protected $appends = ['newtime','difftime'];

     public function getNewtimeAttribute(){ 
        return Carbon::parse($this->created_at)->diffForHumans;
     }

     public function getDifftimeAttribute(){
        return Carbon::now()->diff(Carbon::parse($this->created_at));
     }
}

Any attributes listed in the $appends property will automatically be included in the array or JSON form of the model, provided that you've added the appropriate accessor.

Balraj Allam
  • 611
  • 6
  • 24
  • OK that works....but it returns the date as it is in DB table (MySql) and is there a way to get the date localized....how to set carbon to be global – lewis4u Oct 27 '16 at 14:06
  • you can refer to this link to set carbon instance globally http://stackoverflow.com/a/25939511/4584028 – Balraj Allam Oct 27 '16 at 14:11