See if there's anything in this article that will help https://scotch.io/tutorials/easier-datetime-in-laravel-and-php-with-carbon
Date Accessor: Model Date to Human Carbon Date
UPDATED APRIL 2017
If you need to access a column date as human date here is how:
2.Inside of your model:
// NOTE : Carbon date setup is not required for accessor for human dates i.e. you can remove form your model if you don't want model to cast date to string
/**
* Carbon date setup
*
* @return array
*/
public function getDates()
{
return ['created_at', 'updated_at'];
}
/**
* @return string
*/
public function getCreatedAtAttribute()
{
return Carbon::parse($this->attributes['created_at'])->diffForHumans();
}
/**
* @return string
*/
public function getUpdatedAtAttribute()
{
return Carbon::parse($this->attributes['updated_at'])->diffForHumans();
}
9 MONTHS AGO
for some reason it was difficult to find a simple answer. If you need to access a column date as human date here is how:
1.when you create a custom date columns, lets say 'published_at' ensure that the you create the column with $table->timestamp('published_at'); if you use $table->datetime( )or any other date / time stamp you can run into accessor issues.
2.Inside of you model ensure you have $getDates to include the custom column name i.e. 'published_at' :
/**
* Carbon date setup
*
* @return array
*/
public function getDates()
{
return ['created_at', 'updated_at', 'published_at'];
}
3.AND that you also have have time stamp set to true in your model i.e.
/**
* Indicates if the model should be timestamped.
*
* @var bool
*/
public $timestamps = true;
4.then create the accessor. In the cast of 'published_at' you method name would be ' getPublishedAtAttribute'. Both of these work
/**
* Published at accessor
*
* @param $date
* @return string
*/
public function getPublishedAtAttribute($date)
{
return Carbon::parse($date)->diffForHumans();
}
OR
/**
* Published at accessor
*
* @param $date
* @return string
*/
public function getPublishedAtAttribute($date)
{
return $this->attributes['published_at'] = Carbon::parse($date)->diffForHumans();
}
5.you then access it as follows:
$getArticle = Article::find(1);
// object method
$getArticle->published_at
OR
// array example
$getArticle->toArray()['published_at']
hope that helps
Please or to participate in this conversation.