You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel中如何自定义设置created_at字段的指定日期?

如何在Laravel中为created_at设置指定日期而非默认值?

嘿,我完全懂你在Laravel里手动设置created_at时的挫败感——默认的自动时间戳总像是“抢跑”一样覆盖你想要的自定义日期对吧?别担心,我给你整理几个亲测有效的解决办法,帮你搞定这个问题:

方法1:用forceCreate()绕过自动时间戳限制

Laravel的默认create()方法会自动忽略created_at字段(因为框架默认维护这个字段),但forceCreate()会绕过这个限制,直接填充所有你在$fillable里声明的字段。步骤如下:

首先确保你的模型里把created_at加入到$fillable数组中:

// app/Models/YourModel.php
protected $fillable = ['name', 'email', 'created_at']; // 把created_at加进来

然后直接用forceCreate()创建模型并指定日期:

use Carbon\Carbon;
use App\Models\YourModel;

YourModel::forceCreate([
    'name' => '测试用户',
    'email' => 'test@example.com',
    'created_at' => Carbon::parse('2023-09-15 10:20:30'), // 可以传Carbon实例或可解析的日期字符串
]);

方法2:临时关闭模型的自动时间戳

你可以在创建模型实例时手动关闭timestamps属性,这样Laravel就不会自动填充created_at和updated_at,你就能完全自定义这些值:

use Carbon\Carbon;
use App\Models\YourModel;

$model = new YourModel();
$model->timestamps = false; // 关闭自动时间戳维护
$model->name = '测试用户';
$model->email = 'test@example.com';
$model->created_at = Carbon::parse('2023-09-15 10:20:30');
$model->updated_at = Carbon::now(); // 如果需要自定义updated_at也可以这么设
$model->save();

方法3:创建后用setCreatedAt()覆盖默认值

如果已经用常规create()方法创建了模型,也可以事后调用setCreatedAt()方法来修改created_at的值,然后保存:

use Carbon\Carbon;
use App\Models\YourModel;

$model = YourModel::create([
    'name' => '测试用户',
    'email' => 'test@example.com',
]);

$model->setCreatedAt(Carbon::parse('2023-09-15 10:20:30'));
$model->save(); // 保存修改

关于日期格式和Mutators的注意点

  • 尽量直接传Carbon实例,避免格式不兼容的问题;如果传字符串,确保是Carbon能解析的格式(比如Y-m-d H:i:s)。
  • 如果你用了Mutators(修改器),要确保修改器的逻辑正确,比如:
public function setCreatedAtAttribute($value)
{
    $this->attributes['created_at'] = Carbon::parse($value)->format('Y-m-d H:i:s');
}

不过要注意:默认情况下Laravel自动维护时间戳时,这个修改器不会触发,所以最好结合上面的方法(比如关闭自动时间戳或用forceCreate())一起使用,才能让修改器生效。

内容的提问来源于stack exchange,提问作者Joumana Issa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 04:10:15