Migration - down: check if table has column

One of the problem with database migrations in Laravel is developers rarely actually test "down" migrations - even when testing we usually re-generate the whole schema from scratch instead of launching down() functions. Therefore I would advice to check something before doing down migrations. Common example in my experience - adding a new column to existing table. In up() function we're adding the column, and in down() we're removing it. Something like this:
    public function up()
    {
        Schema::table('users', function (Blueprint $table)
        {
            $table->string('phone')->nullable()->after('email');
        });
    }

    public function down()
    {
        Schema::table('users', function (Blueprint $table)
        {
            $table->dropColumn('phone');
        });
    }
Now, if we're doing migrate:rollback and for whatever reason that column doesn't exist in the table, it will throw an error. So a proper way is to add an if-statement.
    public function down()
    {
        if (Schema::hasColumn('users', 'phone'))
        {
            Schema::table('users', function (Blueprint $table)
            {
                $table->dropColumn('phone');
            });
        }
    }
Similarly you can add if-statements like this in other parts of your migrations, it just depends on your level of "paranoia" and the odds that someone would change the database structure outside the migrations scripts - for example, manually via phpMyAdmin or Sequel Pro clients.

No comments yet…

Like our articles?

Become a Premium Member for $129/year or $29/month

Written by

You might also like