samedi 5 septembre 2020

Laravel inserts `0000-00-00` instead of null when DB is set to `->nullable()` and `->default(null)`

I'm using Laravel 5.1 on a Homestead Vagrant box, PHP 7.2.14 on Ubuntu 18.04 with MySql 5.7.25.

I have created a migration with this:

$table->date('expiry_date')->nullable()->default(null);

I have a form with a date field called expiry_date, with a default set to null:

{!! Form::date('expiry_date', null, array('class' => 'form-control')) !!}

When I enter a date in the field everything works fine, but when I leave it blank it inserts 0000-00-00 into the database, which then messes up the display in my view. The only way I've been able to fix it is by adding this to the model:

public function setExpiryDateAttribute($value)
{
    $this->attributes['expiry_date'] = $value ?: null;
}

I'm annoyed that I have to do this extra step, and it doesn't feel very "Laravel" which makes me believe I'm missing something.

Interesting thing is that it passes validation in my custom Request:

'expiry_date' => 'date',

EDIT:

I have protected $dates ['expiry_date'] set in the model and it's been added to mass assignment as well.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire