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

Laravel中如何使用迁移创建的类填充用户表数据

问题解答

首先先明确Laravel的核心功能分工,你存在概念认知偏差:

  • 迁移(Migration)是数据库结构版本控制工具,仅用于定义、修改数据库的表结构,不负责存储用户提交的动态业务数据,你当前用User::create()存储注册数据的写法是Laravel业务层处理数据写入的标准实现,不需要替换成迁移操作。
  • 你当前代码运行异常的核心原因是:迁移文件定义的users表存在多个非空字段,但你的注册表单、写入逻辑没有传递这些字段的值,导致写入数据库时报非空约束错误。

具体修复步骤

1. 先修正迁移文件的不合理设计

你当前迁移文件的字段名存在特殊字符、非空字段不符合业务逻辑,建议调整:

<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateUsersTable extends Migration
{
    public function up()
    {
        Schema::create('users',function (Blueprint $table) {
            $table->increments('id');
            $table->string('surname',255)->nullable(false);
            $table->string('name',255)->nullable(false);
            $table->string('number',255)->nullable(false)->unique();
            // 把带特殊符号的字段名改成下划线命名,避免SQL语法错误
            $table->string('father_name',255)->nullable(); // 非必填字段改nullable
            $table->string('parent_number',255)->nullable();
            $table->string('password',255)->nullable(false);
            $table->string('studies',255)->nullable();
            $table->string('classes',255)->nullable();
            $table->string('remember_token',100)->nullable(true);
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::dropIfExists('users');
    }
}

修改完后执行php artisan migrate:fresh重置表结构(注意会清空现有数据,生产环境谨慎操作)。

2. 修正注册控制器的密码加密逻辑

你当前直接存储明文密码,Laravel的Auth认证要求密码必须经过Hash加密,修改RegisterController的create部分代码:

$user = User::create([
    'password' => Hash::make($request['password']), // 加密密码
    'name' => $request['name'],
    'surname'=>$request['surname'],
    'number'=>$request['number']
]);

3. 如果需要插入初始化固定用户数据,用种子器(Seeder)

如果你是要提前写入固定的测试用户数据,不要用迁移,Laravel专门提供了种子器用于初始化数据:

  1. 执行php artisan make:seeder UsersTableSeeder生成种子文件
  2. 在种子文件的run方法中写入测试数据:
public function run()
{
    User::create([
        'surname' => '测试姓',
        'name' => '测试名',
        'number' => '13800000000',
        'password' => Hash::make('123456')
    ]);
}
  1. 执行php artisan db:seed --class=UsersTableSeeder即可插入初始化数据。

其他代码优化点

  • 注册视图registration.blade.php里的<h1>登录</h1>改成<h1>注册</h1>,字段number的label错误写为「姓名」,建议修正
  • 可以在注册验证规则里加password的长度校验,避免用户设置过短密码

内容的提问来源于stack exchange,提问作者Дмитрий Гвоздиенко

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.10 01:27:00