Published on

Quick Tip for Migrations: Check if Table/Column Already Exists

Authors

Many times we have face issue/difficulties on either small or big project create a laravel migration for the same table or column that already exist. which fire error when we run the migration command

Luckily laravel has built-in methods to handle such issues.

Normal migration table code looks like below one:

public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->timestamps();
    });
}

Now, users table already exists and you run migration command then it'll give you error. users table already exists something like that. As a solution, we can use Schema::hasTable('users') to check whether the table I exist already or not.

public function up()
{
    if ( !Schema::hasTable('users') ) {
        Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->timestamps();
        });
    }
}

So, If users table does not exist then it creates otherwise it'll ignore it.

Laravel also has a function to check column exist or not but it's a rare case to have such use I think,

public function up()
{
    if (Schema::hasTable('users')) {
        Schema::table('users', function (Blueprint $table) {
            if (!Schema::hasColumn('users', 'name')) {
                $table->string('name');
            } 
        });
    }
}

you can find more details from laravel official documentation.