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

Laravel 10中如何为date类型字段设默认值?插入记录报错求助

解决方法

1. 数据库迁移层面设置默认值(最可靠)

修改posts表的迁移文件,给post_date字段设置默认值为当前日期,同时保留非空约束:

Schema::create('posts', function (Blueprint $table) {
    $table->id();
    $table->string('username');
    $table->text('post');
    // 用数据库原生函数设置默认值为当前日期
    $table->date('post_date')->default(DB::raw('CURRENT_DATE'));
    $table->timestamps();
});

执行迁移更新数据库后,插入记录时如果不传入post_date,数据库会自动填充当前日期,彻底避免报错。

2. 模型层面设置属性默认值

在Post模型中通过$attributes数组或构造函数动态设置默认值:

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Carbon\Carbon;

class Post extends Model
{
    protected $fillable = [
        'username',
        'post',
        'post_date',
    ];

    // 方式1:直接定义静态默认值
    protected $attributes = [
        'post_date' => '',
    ];

    // 方式2:初始化时动态填充当前日期
    public function __construct(array $attributes = [])
    {
        parent::__construct($attributes);
        if (!isset($this->attributes['post_date'])) {
            $this->attributes['post_date'] = Carbon::now()->toDateString();
        }
    }
}

调用Post::create()时,即便不传入post_date,模型会自动补全合法的日期值。

3. 控制器层面手动补充默认值

在创建记录前,手动向数组中添加post_date的合法值:

use App\Models\Post;
use Carbon\Carbon;

Post::create([
    'username' => 'ABC',
    'post' => 'DEF',
    'post_date' => Carbon::now()->toDateString(),
]);

这种方式适合需要自定义默认值逻辑的场景。

失败原因说明

  • 传入null:数据库中post_date字段设置了非空约束,直接触发完整性错误;
  • 传入'0000-00-00':MySQL严格模式(Laravel默认开启)下,该值属于无效日期,被数据库拒绝;
  • 传入空字符串:不符合date类型的格式规范,数据库无法解析。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 07:27:39