skip to Main Content

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.

3

Answers


  1. 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

    Login or Signup to reply.
  2. you need to add nullable to the gender field in the migration

    $table->type('gender')->nullable();
    
    Login or Signup to reply.
  3. 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' => '[email protected]',
      '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.
    ];
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search