如何实现 laravel 自定义碳时间戳?

How to implement laravel custom carbon timestamp?

我想要 'contests' 的未来时间戳,该时间戳在我的 table 中到期。我可以毫无问题地输入时间,除了当我检索输入时它似乎 return 我不是一个碳实例,而只是一个带有时间的字符串?

public function store(ContestRequest $request)
{
    $input = Request::all();

    // Set the 'owner' attribute to the name of the currently logged in user(obviously requires login)
    $input['owner'] = Auth::user()->name;

    // Set the enddate according to the weeks that the user selected with the input select
    $weeks = Request::input('ends_at');

    // Add the weeks to the current time to set the future expiration date
    $input['ends_at'] = Carbon::now()->addWeeks($weeks);

    Contest::create($input);

    return redirect('contests');
}

这就是我用来创建新比赛的内容,table 中的时间格式与 created_at 和 updated_at 字段中的时间格式完全相同。当我尝试类似的东西时,它们似乎 return Carbon 实例:

$contest->created_at->diffForHumans()

为什么我没有得到 carbon 实例 returned?

我的迁移文件如下所示:

$table->timestamps();
$table->timestamp('ends_at');

Laravel 仅将其默认时间戳转换为 Carboncreated_atmodified_at)。对于任何其他时间戳(例如您的 ends_at 列),您可以在 Contest 模型中定义一个 属性 访问器:

public function getEndsAtAttribute($value)
{
    return Carbon::createFromTimeStamp(strtotime($value));
}

当您调用 $contest->ends_at.

时,这将从数据库返回的 datetime 字符串转换为 Carbon 实例

您只需将其添加到模型中的 $dates 属性。

class Contest extends Model {
    protected $dates = ['ends_at'];
}

这告诉 Laravel 像对待 updated_atcreated_at

一样对待您的 ends_at 属性

@Jakobud 您不必担心覆盖 created_atupdated_at。它们将与 $dates 数组合并:

public function getDates()
{
    $defaults = array(static::CREATED_AT, static::UPDATED_AT);
    return array_merge($this->dates, $defaults);
}

static::CREATED_AT 解析为 'created_at'static::UPDATED_AT 解析为 'updated_at'