Laravel 5.5。* SQLSTATE [23000]:违反完整性约束:19 NOT NULL约束失败

时间:2019-09-29 09:02:25

标签: php database sqlite laravel-5 laravel-blade

我正在尝试使用Laravel提供的RegistrationController将新用户添加到我的数据库中。每当我尝试注册一个新用户时,即使我没有提交任何空字段,它也会打出错误,提示非空约束失败。起初,我以为地址字段是一个问题,直到我在迁移中使其变为可空值以解决错误为止,并且下一个字段的非null约束也失败了。我已经仔细检查了我所有的迁移文件,甚至转储了我要传递到数据库中的数据以仔细检查没有任何内容为null。该错误消息告诉我,它甚至没有试图将我提供的信息传递给数据库,但是我不知道如何解决此问题。

我的迁移:

    Schema::create('users', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->string('password');
            $table->string('address');
            $table->string('user_type');
            $table->boolean('approved')->nullable();
            $table->rememberToken();
            $table->timestamps();
        });

我在注册控制器中的创建功能:

    protected function create(array $data)
    {
        return User::create([
            'address' => $data['address'],
            'name' => $data['name'],
            'email' => $data['email'],
            'user_type' => $data['user_type'],
            'password' => Hash::make($data['password'])
        ]);
    }

我的数据转储的结果:

       array:7 [▼
  "_token" => "d5qCwoIqyfiF1q5FyAIhi3gHEm5CA7OHpDZVRKSI"
  "name" => "test"
  "email" => "asasdfasd@sdfgsdfgg.com"
  "address" => "1637 test street"
  "user_type" => "Customer"
  "password" => "12345678"
  "password_confirmation" => "12345678"
]

还有我得到的错误:

SQLSTATE[23000]: Integrity constraint violation: 19 NOT NULL constraint failed: 
users.address (SQL: insert into "users" ("name", "email", "password", "updated_at", "created_at") 
values (test, asasdfasd@sdfgsdfgg.com, $2y$10$q1Kc0A80cd0ARJbvTtpiee59fJ8g4orilFWjNV5igihPDWQeoYhjG, 2019-09-29 08:57:58, 2019-09-29 08:57:58))

任何人能提供我的帮助将不胜感激。如果您需要我的代码的更多摘要,请告诉我。谢谢你。

1 个答案:

答案 0 :(得分:1)

在模型中,应添加fillable属性以允许进行批量分配。

class User extends Model
{
    protected $fillable = [
        'address', 'name', 'email', 'password', 'user_type'
    ];
}

或仅使用

class User extends Model
{
    protected $guarded = [];
}