jbowman99's avatar

Timestamp Nullable throwing error when Null

I have a form with several date inputs, majority of them are nullable fields, receiving this error when the field is left blank

Invalid datetime format: 1292 Incorrect datetime value:

form looks like this:


<div class="form-group">
            {!! Form:: label('date_of_visitation','Date:' ) !!}
            {!! Form:: input('date', 'date_of_visitation', null, ['class' => 'form-control', 'placeholder' => 'MM/DD/YYYY']) !!}
        </div>

Migration looks like this:

 $table->timestamp('date_of_visitation')->nullable();

when this was in Sqlite it worked fine, now in mysql it throws that error Any Suggestions??

0 likes
5 replies
phildawson's avatar

In the controller dump out what is being sent when it's not being filled in.

dd($request->all());

Does it have?

'date_of_visitation' => ''
phildawson's avatar
Level 26

Yeah so it prob needs this in the Model

use Carbon\Carbon;
public function setDateOfVisitationAttribute($value)
{
$this->attributes['date_of_visitation'] = !empty($value) ? Carbon::createFromFormat('m/d/Y',$value) : null;
}
2 likes
jbowman99's avatar

@phildawson

So that fixed my issue, what is going on in there? am I sending a format that MySql doesn't understand?

phildawson's avatar

@jbowman99

Edit: I've done some checking and it doesn't do this unless 'strict' => true, in config so ¯(°_o)/¯

it's because mysql is set to a strict mode so instead of inserting 0000-00-00 00:00:00 and giving a warning it will instead produce an error halting the query from being executed.

As an eg

Default (inserts but gives a warning)

mysql> INSERT INTO xxx (`date_of_visitation`) VALUES ('');
Query OK, 1 row affected, 1 warning (0.01 sec)

mysql> SHOW WARNINGS;
+---------+------+---------------------------------------------------------+
| Level   | Code | Message                                                 |
+---------+------+---------------------------------------------------------+
| Warning | 1265 | Data truncated for column 'date_of_visitation' at row 1 |
+---------+------+---------------------------------------------------------+

As Laravel runs:

mysql> set session sql_mode='STRICT_ALL_TABLES';
Query OK, 0 rows affected (0.00 sec)

mysql> INSERT INTO xxx (`date_of_visitation`) VALUES ('');
ERROR 1292 (22007): Incorrect datetime value: '' for column 'date_of_visitation' at row 1

The code I supplied basically does a check to say is it empty well set the value to null like doing.

mysql> INSERT INTO xxx (`date_of_visitation`) VALUES (NULL);
Query OK, 1 row affected (0.00 sec)

And as its nullable(); it's all good. :)

2 likes

Please or to participate in this conversation.