Home > Software design >  "nullable" database column gives error "cannot be null" when creating a new row
"nullable" database column gives error "cannot be null" when creating a new row

Time:11-06

I am in despair. I've already invested hours and just can't get any further. Maybe someone can help me.

There is a Model called "Ladders". In my migrations I create a nullable "description" field. I've run the migration.

Schema::create('ladders', function (Blueprint $table) {
    $table->id();
    $table->string('name');
    $table->string('slug')->unique;
    $table->text('description')->nullable;
    $table->date('date_start');
    $table->date('date_end');
    $table->timestamps();
});

In my Model Ladder.php the field is defined as "fillable".

protected $fillable = [
    'name',
    'slug',
    'description',
    'date_start',
    'date_end'
];

In the respective Controller I have the default store method. It should validate my POST request and create a new entry in the database.

public function store(Request $request)
{
    $request->validate([
        'name' => 'required',
        'slug' => 'prohibited',
        'description' => 'nullable|string',
        'date_start' => 'required|date',
        'date_end' => 'required|date|after:start_date'
    ]);

    $request['slug'] = Str::slug($request->name);

    return Ladder::create($request->all());
}

But I'm getting the following error messages, when trying to create a new entry via API endpoint.

When I omit the "description" completely from the request:

SQLSTATE[HY000]: General error: 1364 Field 'description' doesn't have a default value (SQL: insert into `ladders` (`name`, `date_start`, `date_end`, `slug`, `updated_at`, `created_at`) values (Test Name, 2020-10-08, 2020-10-08, test-name, 2022-11-05 22:33:33, 2022-11-05 22:33:33)) 

When I submit the "description" field with my request, but leave it empty:

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'description' cannot be null (SQL: insert into `ladders` (`name`, `date_start`, `date_end`, `description`, `slug`, `updated_at`, `created_at`) values (Test Name, 2020-10-08, 2020-10-08, ?, test-name, 2022-11-05 22:30:54, 2022-11-05 22:30:54)) 

I don't get it. If the field is defined as "nullable" can't I just omit it in a request? What am I doing wrong?

I tried to get rid of the validation. But this is not what I want, the data should be validated, when given.

I tried to send non empty strings, then it's obviously working. But I would like to be able to omit this field.

CodePudding user response:

If im not mistaken... u gotta use ->nullable(); and not nullable;

and return Ladder::create($request->all()); returns the UNVALIDATED data safe it in a variable like $validated and then go like Ladder::create($validated)

  • Related