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

Laravel 5.1.x how to manipulate date correctly?

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

等常见日期一起插入

Little Side note这是API系统的一部分,完全不依赖forms和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,虽然它是 returns 日期的 Carbon 实例,但它只是 returns 一个字符串

/**
 * 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?我不介意处理 ALL 日期时间,因为 created_atupdated_atdeleted_at 已经在幕后处理了

TL;DR

is there a better method to batter handling DateTime using mutators in Laravel 5.1.x? I don't mind to handle ALL date time since created_at, updated_at and deleted_at are already handled behind the curtains

有了 laravel 5.2 就没必要了

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

的模型中
protected $dates=['activated_at'];

而且你不需要任何getter方法来获取碳对象,你可以直接在你的controller.Take用户模型中调用它的函数,例如:

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