Laravel Auth注册报错:SQLSTATE[HY000]常规错误1364字段未赋值
嘿,这个报错我太熟了!本质就是你的数据库里address、city、zipcode这些字段被标记为NOT NULL(不允许为空),但你注册的时候根本没提交这些值,MySQL自然就炸了。给你几个一步步解决的方案:
解决步骤
1. 搞定数据库字段的可空性(最根本的办法)
因为这些字段是用户后续补充的,注册时本来就不该必填,所以得把它们改成允许为空:
- 如果是本地开发且没重要数据,直接修改最初的用户表迁移文件(比如
database/migrations/xxxx_xx_xx_xxxxxx_create_users_table.php),把字段定义改成:
$table->string('address')->nullable(); $table->string('city')->nullable(); $table->string('zipcode')->nullable();
然后执行迁移刷新(会清空用户表数据):
php artisan migrate:refresh
- 如果是生产环境或已有重要数据,新建一个修改字段的迁移:
php artisan make:migration alter_users_set_profile_fields_nullable --table=users
在生成的迁移文件里写:
public function up() { Schema::table('users', function (Blueprint $table) { $table->string('address')->nullable()->change(); $table->string('city')->nullable()->change(); $table->string('zipcode')->nullable()->change(); }); } public function down() { Schema::table('users', function (Blueprint $table) { $table->string('address')->nullable(false)->change(); $table->string('city')->nullable(false)->change(); $table->string('zipcode')->nullable(false)->change(); }); }
最后执行迁移:
php artisan migrate
2. 确保User模型支持批量赋值
打开app/Models/User.php,把这些可选字段加到$fillable数组里,这样后续用户编辑资料时能正常保存:
protected $fillable = [ 'name', 'surname', 'email', 'password', 'address', 'city', 'zipcode', ];
3. 调整注册控制器的创建逻辑(双重保险)
打开app/Http/Controllers/Auth/RegisterController.php,找到create方法,只处理注册时必填的字段,别碰那些可选字段:
protected function create(array $data) { return User::create([ 'name' => $data['name'], 'surname' => $data['surname'], 'email' => $data['email'], 'password' => Hash::make($data['password']), // 这里不要写address、city等字段,数据库会自动存null ]); }
额外提醒:注册表单的验证规则
确保你的注册请求验证(不管是单独的Request类还是控制器里的验证逻辑)只校验必填字段,别把address这些加进去:
return Validator::make($data, [ 'name' => ['required', 'string', 'max:255'], 'surname' => ['required', 'string', 'max:255'], 'email' => ['required', 'string', 'email', 'max:255', 'unique:users'], 'password' => ['required', 'string', 'min:8', 'confirmed'], // 不要出现address、city、zipcode的验证规则 ]);
这样改完之后,注册时就不会再报那个1364的错误了,用户后续编辑资料补充这些字段也能正常保存~
内容的提问来源于stack exchange,提问作者user9297268
相关产品推荐
相关产品推荐

