我想为表中过期的"竞赛"提供一个未来的时间戳。我可以毫无问题地输入时间,除非当我检索输入时,它似乎不会给我返回一个carbon实例,而只是一个带时间的字符串?
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');
}
这就是我用来创建新比赛的内容,表中的时间格式与created_at和updated_at字段完全相同。当我尝试类似的东西时,他们似乎返回了一个Carbon实例
$contest->created_at->diffForHumans()
为什么我没有得到一个碳实例返回?
我的迁移文件如下:
$table->timestamps();
$table->timestamp('ends_at');
您所要做的就是将其添加到模型中的$dates
属性中。
class Contest extends Model {
protected $dates = ['ends_at'];
}
这条消息告诉Laravel将您的ends_at
属性处理为与处理updated_at
和created_at
相同的属性
@Jakobud您不必担心覆盖created_at
和updated_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'
Laravel仅将其默认时间戳转换为碳(created_at
,modified_at
)。对于任何其他时间戳(例如ends_at
列),您可以在Contest
模型中定义一个属性访问器:
public function getEndsAtAttribute($value)
{
return Carbon::createFromTimeStamp(strtotime($value));
}
当您调用$contest->ends_at
时,这将把从数据库返回的datetime
字符串转换为Carbon
实例。