5

I have to add a new column to an existing table that already has data in it and running into a bit of a hiccup.

  1. How can I add this column? Its going to be a Not Nullable field. I'm ok with populating it with default data for right now and going back and updating later. so if we need to drop constraints while adding. I'm assuming I'm going to need to utilize straight SQL queries.

  2. Make this work w/ PHPUnit and SQLite, currently I'm getting an error SQLSTATE[HY000]: General error: 1 Cannot add a NOT NULL column with default value NULL (SQL: alter table "tracks" add column "short_description" text not null)

How would I modify this migration?

public function up()
{
    Schema::table('tracks', function(Blueprint $table)
    {
        $table->text('short_description')->after('description');
    });
}
3
  • you have to change your default value as well, just like the error says. You cannot have a null default value on a field which is not null. That's an outright contradiction. Commented Mar 10, 2014 at 17:01
  • what kinda throws me for a curve, is I already have a description column on the table thats the same as the short description. $table->text('description'); its created when the migration runs to create the table and seems to work just fine. :/ However, if I look at a description of the DB table in mysql I can clearly see it creates the column as NOT NULL, but with a NULL default value. And I can't set a default value on a text column. Which is why I was thinking I would have to drop the constraints on the table while the column was being created, and push in a temp default. Commented Mar 10, 2014 at 17:10
  • found this snippet in another answer. "when creating a table for the first time, it's fine to have some columns be not nullable, but when altering and adding a column, even though the table is empty, for some reason it balks." Commented Mar 10, 2014 at 19:14

1 Answer 1

4

You have to set default value:

public function up()
{
    Schema::table('tracks', function(Blueprint $table)
    {
        $table->text('short_description')->after('description')->default('default_value');
    });
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.