如何在模型本身的 Laravel 中将 unix 时间戳转换为 Carbon 实例?

aru*_*run 1 laravel

我已经拥有的:

在模型中有这个:

protected $dates = [ 'applied_date' ];
Run Code Online (Sandbox Code Playgroud)

在数据库中applied_date就是以这种格式存储的2018-05-11 13:31:59

因此,我可以将其格式化如下:

$applied_date->format('m/d/Y')
Run Code Online (Sandbox Code Playgroud)

我想要的是:

在数据库applied_date中已经以这种格式存储1530205690(unix 时间戳)。

我想在视图中格式化,$applied_date->format('m/d/Y')我该如何实现?

注意:我们可以 Carbon::createFromTimestamp($applied_date)->format('m/d/Y');

jaf*_*690 6

您可以使用 laravel 属性https://laravel.com/docs/5.6/eloquent-mutators

像这样的东西

/**
 * Get formatted applied_date.
 *
 * @return string
 */
public function getDateAttribute()
{
    $date = Carbon::createFromTimestamp($this->applied_date)->format('m/d/Y');

    return $date;
}
Run Code Online (Sandbox Code Playgroud)

那么在你看来你可以这样做 {{ $model->date }}