Logo Questions Linux Laravel Mysql Ubuntu Git Menu

Should I always provide default value in php for TEXT fields in mysql

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?

like image 308
Mihai Crăiță Avatar asked Mar 20 '23 13:03

Mihai Crăiță

1 Answers

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, "");


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 = '';


$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' => '');

like image 171
Unnawut Avatar answered Mar 22 '23 11:03