I try to insert a new record in a table using Eloquent ORM included with Laravel Framework the insert statement resulted is as follows:
INSET INTO
table_x
(field_x
,field_y
,field_z
) VALUES (0, 1, 2)
I receive the following error from MySQL Server:
SQLSTATE[HY000]: General error: 1364 Field 'field' doesn't have a default value
I do not provide the field in my INSERT statement. The field is of type TEXT and from MySQL docs: "BLOB and TEXT columns cannot have DEFAULT values".
So I always have to provide myself a default value in my php code for TEXT fields? Or maybe should Eloquent take care of this and set an empty string automatically on insert?
MySQL does not support having default values in TEXT columns. So you have to manually tell Laravel/MySQL what to put in that column. For example.
INSERT INTO table_x (field_x, field_y, field_z, your_text_field) VALUES (0, 1, 2, "");
or
INSERT INTO table_x (field_x, field_y, field_z, your_text_field) VALUES (0, 1, 2, NULL);
So in your Eloquent model, you'll have to do something like.
$myModel->your_text_field = '';
or
$myModel->your_text_field = null;
Depending on whether you have set your column to be nullable or not.
Update: As Mihai Crăiță the question author commented in my answer, and in GitHub ticket, we can set a default for any columns in the Eloquent model this way, so we don't need to worry about having to set manually all the time.
class MyModel extends Eloquent
{
protected $attributes = array('your_text_field' => '');
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With