Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drop and then create same columns in current up migration function

Schema::table('users', function (Blueprint $table) {
            $table->dropTimestamps();
            $table->dropColumn(['email', 'bio']);

            $table->string('email', 20)->unique()->after('id');
            $table->string('bio', 150)->after('surname');
            $table->timestamps();
        });

That is what I've got now. So, I have the columns existing atm in my table, but I want to modify and re-arrange them a bit. But when I run the migration, I get SQL error that email column exists. And I will probably get the same error for the bio and timestamps as well. I kind of understand why this happens, so what am I asking is just for a workaround.

Is it possible to make what I want inside one single migration, or I have to create a migration for deleting the columns and then a separate migration for creating them the way I want?

like image 360
Milkncookiez Avatar asked Nov 30 '22 18:11

Milkncookiez


2 Answers

Just break the schema up into two calls

public function up()
{
    Schema::table('users', function (Blueprint $table) {
        $table->dropTimestamps();
        $table->dropColumn(['email', 'bio']);
    });

    Schema::table('users', function (Blueprint $table) {
        $table->string('email', 20)->unique()->after('id');
        $table->string('bio', 150)->after('surname');
        $table->timestamps();
    });
}

This way the change is occurring in one migration with two database calls.

like image 176
Laurence Avatar answered Dec 04 '22 00:12

Laurence


Consider that if you drop the columns, you will lose ALL THE DATA contained therein. Normally this is a very bad and dangerous idea. If you instead need to simply change parameters, you should use the change() function to make the required modifications to your schema. This will convert the existing data to the best of your databases's ability.

NEVER DROP COLUMNS on an in-use database unless you absolutely know what you're doing.

    public function up()
    {
        Schema::table('users', function (Blueprint $table) {
            // Add the unique constraint, for example
            $table->string('email', 20)->unique()->after('id')->change();
            // Add the length to the bio, for example
            $table->string('bio', 150)->after('surname')->change();
        });
    }

    public function down()
    {
        Schema::table('users', function (Blueprint $table) {
            // Remove length and constraints
            $table->string('email')->unique(false)->change();
            $table->string('bio')->change();
        });
    }
like image 24
Oranges13 Avatar answered Dec 03 '22 23:12

Oranges13