Laravel Eloquent 更新created_at 值

问题描述 投票:0回答:4

我需要更改帖子的created_at,因为我根据created_at向本月创建的帖子发送短信。当我尝试使用此created_at时,值不会改变!

public function Controller(Posts $post){
    $post->update(['created_at'=>Carbon::today()]);
}
php laravel laravel-5 laravel-5.3 php-carbon
4个回答
10
投票

created_at
通常不是这样的 质量分配。您可能需要将其添加到
$fillable
模型上的
Post
属性,例如:

protected $fillable = [...., 'created_at']; 

请注意,正如其他人指出的那样,

Carbon::today()
似乎不是正确的使用方式 - 它可以工作并提供有效的时间戳,但时间戳是午夜的。如果您确实想要更改的实际时间,您可能需要
Carbon::now()


1
投票

试试这个

public function Controller(Posts $post){
      $post->created_at = Carbon::today();
      $post->save(['timestamps' => false]);
}

1
投票

Carbon::today()
实际上并未生成有效的时间戳。您需要使用
Carbon::today()->toDateTimeString()
来获取有效的时间戳。

更新片段:

public function Controller(Posts $post){
    $post->update(['created_at' => Carbon::today()->toDateTimeString()]);
}

0
投票

您还可以使用 $guarded 允许所有其他属性可填充

protected $guarded = ['id'];

请参阅有关 GuardsAttributes

的雄辩文档
© www.soinside.com 2019 - 2024. All rights reserved.