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

Laravel新增用户表字段后注册报错SQLSTATE[HY000]:1364求助

解决Laravel注册时SQLSTATE[HY000]: 1364字段无默认值的问题

这个报错本质是数据库要求phone_number字段必须有值,但你注册时既没提交该字段的值,数据库也没设置默认值,咱们一步步排查解决:

1. 检查数据库迁移文件的字段设置

首先看你添加phone_number和position的迁移文件(比如add_phone_and_position_to_users_table.php),这两个字段是不是既没设置允许为空,也没给默认值?

如果你的迁移代码是这样的:

Schema::table('users', function (Blueprint $table) {
    $table->string('phone_number');
    $table->string('position');
});

那问题就出在这——默认情况下Laravel的字符串字段是NOT NULL约束,必须二选一:

  • 允许为空(推荐,适合用户后续补充信息的场景):
Schema::table('users', function (Blueprint $table) {
    $table->string('phone_number')->nullable();
    $table->string('position')->nullable();
});
  • 设置默认值(适合必须有值但可以用占位内容的场景):
Schema::table('users', function (Blueprint $table) {
    $table->string('phone_number')->default('');
    $table->string('position')->default('');
});

如果已经执行过迁移,你可以回滚后重新执行:

php artisan migrate:rollback
php artisan migrate

如果怕影响已有数据,也可以创建新的迁移来修改字段属性。

2. 确保User模型允许批量赋值

打开app/Models/User.php(Laravel 8+)或者app/User.php(旧版本),检查$fillable数组,必须把phone_number和position加进去,不然Laravel会自动过滤这两个字段,导致无法插入数据库:

protected $fillable = [
    'name',
    'email',
    'password',
    'phone_number', // 新增字段
    'position',     // 新增字段
];

3. 检查注册视图的表单输入

打开你的注册blade文件(比如resources/views/auth/register.blade.php),确保已经添加了phone_number和position的输入框,并且name属性完全匹配字段名:

<div class="form-group">
    <label for="phone_number">手机号</label>
    <input id="phone_number" type="text" class="form-control" name="phone_number" value="{{ old('phone_number') }}" required>
</div>

<div class="form-group">
    <label for="position">职位</label>
    <input id="position" type="text" class="form-control" name="position" value="{{ old('position') }}" required>
</div>

如果业务允许这两个字段可选,记得去掉required属性,同时对应调整验证规则。

4. 调整注册请求的验证规则

如果你用了Laravel自带的注册请求类(app/Http/Requests/Auth/RegisterRequest.php),打开它的rules()方法,添加phone_number和position的验证规则:

public function rules()
{
    return [
        'name' => ['required', 'string', 'max:255'],
        'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
        'password' => ['required', 'string', 'min:8', 'confirmed'],
        'phone_number' => ['nullable', 'string', 'max:20'], // 根据需求调整规则
        'position' => ['nullable', 'string', 'max:50'],
    ];
}

如果是在控制器的Store方法里直接验证,也要确保包含这两个字段的规则。

5. 排查dd($request->all())无输出的问题

你说执行dd($request->all())只返回错误,大概率是你把dd放在了数据库插入代码之后!应该把它放在Store方法的最开头,这样就能先看到请求里的所有参数:

public function store(Request $request)
{
    dd($request->all()); // 放在最前面,先确认请求有没有带phone_number和position
    
    // 后面的验证、创建用户代码...
}

如果输出里没有这两个字段,那就是视图表单的问题,比如name属性写错了,或者表单没提交这些字段。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 13:07:28