Laravel 5.1.x如何正确操作日期


Laravel 5.1.x how to manipulate date correctly?

我有一个名为activated_at的字段,我想像对待Laravel中的其他日期一样对待它。在数据库中,它是一个时间戳,我将它与常见日期(如updated_atcreated_atdeleted_at)一起插入到$dates数组中。

小提示这是API系统的一部分,该系统完全不依赖于表单和web,因此我无法直接从视图转换数据

问题是,为了正确地设置和获得它,我设置了两个突变体(又名Getter和Setter)。

目前的setter,它不是最好的解决方案,但老实说,我不知道如何创建一个setter,将所有传递的数据转换为适合数据库的数据。我正在使用MariaDB

* Automatically parse the date from metric system to
 * Imperial system because American DATABASES
 *
 * @param string $value
 */
public function setActivatedAtAttribute($value)
{
    if(!$value instanceof 'DateTime)
    {
        $value = Carbon::createFromFormat('d/m/Y H:i:s', $value)->toDateTimeString();
    }
    $this->attributes['activated_at'] = $value;
}

不管怎么说,这个setters工作得很好,我写了一堆单元测试,我对它们很满意。

真正的问题是getter,我认为它返回日期的Carbon实例,但它只是返回一个字符串

/**
 * Return the correct metric format of the date
 *
 * @param string $value
 * @return string
 */
public function getActivatedAtAttribute($value)
{
    // Because it's a string we cannot use Carbon methods
    // Unless we instantiate a new Carbon object which it stupid
    // Since the activated_at field is inside the $dates array
    // Shouldn't we get the carbon object automatically?
    return $value;
}

我关心的是getter方法内部的注释块。

话虽如此,在Laravel 5.1.x中,是否有更好的方法来使用突变处理DateTime?我不介意处理所有日期时间,因为created_atupdated_atdeleted_at已经在窗帘后面处理了

TL;DR

在Laravel 5.1.x中,是否有更好的方法来使用突变处理DateTime?我不介意处理所有日期时间,因为created_atupdated_atdeleted_at已经在窗帘后面处理了

有了laravel 5.2,就不需要这个

据我所知,在Laravel 5.1中,您应该做的是将以下代码添加到包含字段"activated_at"的模型中。

protected $dates=['activated_at'];

而且你不需要任何getter方法来获得一个碳对象,你可以直接在控制器中调用它的函数

User::findOrFail(1)->activated_at->diffForHumans();