Search code examples
datelaravel-5migrationdefaultnullable

Set a custom dafault date for a nullable date column on Laravel


I want to set a default date of 1900-01-01 on a nullable date field.

I've tried this

$table->date('fecha_nacimiento')->nullable()
    ->default(\Carbon\Carbon::make('1900-01-01')->toDateTimeString());

Also

$table->date('fecha_nacimiento')->nullable()
    ->default(\Carbon\Carbon::make('1900-01-01'));

Also

$table->date('fecha_nacimiento')->nullable()->default('1900-01-01');

When I save from the browser with the HTML date input not set, it saves the date field as null.


Solution

  • The default value on the field only applies when no value, not even null, is assigned.

    The blank value is most likely from a blank input from a form. Also, if you are using eloquent mass assignment like so,

    $model->fill($request->all());
    

    In this case, your date field is set to null and your insert statement will look like this,

    INSERT INTO table_name (fecha_nacimiento, ...)
    VALUES (null, ...);