简体   繁体   中英

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

I'm trying to start a project in laravel and am getting this error while selecting the gender when doing the registration.

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

return User::create([
    'name' => $data['name'],
    'avatar' => $avatar_path,
    'gender' => $data['gender'],
    'email' => $data['email'],
    'password' => Hash::make($data['password']),
]);

If I by the "Gender" Null option in my phpMyAdmin works without errors, but does not show the gender but "NULL."

HTML

<div class="form-group row">
    <label for="name" class="col-md-4 col-form-label text-md-right">Gender</label>

    <div class="col-md-6">
        <select name="gender" class="col-md-4 control-label">
            <option value="male" name="male">Male</option>
            <option value="female" name="female">Female</option>
        </select>

        @error('gender')
        <span class="invalid-feedback" role="alert">
            <strong>{{ $message }}</strong>
        </span>
        @enderror
    </div>
</div>

I already did:

SET GLOBAL sql_mode = '';

I also added SET sql_mode = to PHPMyAdmin, but I keep getting the error.

Looks like you've got the migration correct, using nullable. May I ask if you have removed the old DB and re-migrated with the $table->string('gender')->nullable(); included? Perhaps it's still working on the old database which didn't have the gender field as nullable.

Next thing is to try to just enter data directly to see if the problem is with the DB or with the input coming from the form. Try this:

return User::create([
  'name' => 'testname',
  'avatar' => $avatar_path,
  'gender' => 'MALE',
  'email' => 'aa@bb.com',
  'password' => Hash::make($data['password']),
]);

If that works, the problem is a null coming in from the form AND the DB is not set up to take a null value.

Also, make sure the User model actually has the gender field as fillable. on your User Model , make sure it looks like this:

protected $fillable = [
    'name',
    'avatar',
    'gender',  <--- make sure that gender is here
    // Etc.
];

what is the data dype of gender?

if it is string then you should add nullable in db it its not then you can change your value in form as 0 or 1

您需要在迁移中的性别字段中添加可空值

$table->type('gender')->nullable();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM