Error Field doesn't have a default value in la

2020-04-13 17:18发布

问题:

I have no problem in Laravel 5.2 but in Laravel 5.3 after create migration for user model, It shows me following error:

SQLSTATE[HY000]: General error: 1364 Field 'family' doesn't have a default value !!!

In Model user:

protected $fillable = [
    'name', 'email', 'password', 'family', 'mobile', 'address', 'status'
];

In Migration:

Schema::create('users', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->string('family');
        $table->string('mobile')->unique();
        $table->string('address');
        $table->boolean('status');
        $table->string('email')->unique();
        $table->string('password');
        $table->integer('reagent');
        $table->rememberToken();
        $table->timestamps();
    });

Where is my problem?

回答1:

You should add ->nullable() or ->default('somethingHere') to fields which you send empty values.

$table->string('family')->nullable(); //this means that if you send empty value this field will become MySQL NULL

Or set default value:

$table->string('family')->default('default value here');

Than remigrate:

php artisan migrate:rollback

and

php artisan migrate


回答2:

I found my solutions here is the link: Eloquent create says column has no default value

The answer is at the bottom, i just quoted the answer also

imbhavin95 replied 8 months ago

The reason this is happening now, however, is that Laravel 5.1 uses strict mode for MySQL by default.

If you would like to revert to previous behavior, update your config/database.php file and set 'strict' => false for your connection.

credits to this man https://laravel.io/user/imbhavin95



回答3:

You can make it nullable:

$table->string('family')->nullable();

Or add some default value:

$table->string('family')->default('none');

After that you should back up data and run:

php artisan migrate:refresh                                      

Then restore the data.

Or you could create a separate migration and just change family to a nullable:

Schema::table('users', function (Blueprint $table) {
    $table->string('family')->nullable()->change();
});