Skip to main content

Black Friday 2025! Only until December 1st: coupon FRIDAY25 for 40% off Yearly/Lifetime membership!

Read more here
Tutorial Free

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

January 21, 2019
2 min read

Sometimes, especially in bigger projects, we run into issue of writing a create migration for the same table, or even column that already exist. Luckily, Laravel has a quick way of checking it.

Typical migration looks like this:

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

And if flights table already exists (for whatever reason), you would get an error. Solution to this is Schema::hasTable() method.

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

So, if table flights does not exist, then we create it.

Of course, it can be used in a positive way - for example, if we want to add a new column to existing table, then we may check if table does exist.

Let's combine this with another example and with another method Schema::hasColumn(), which has two parameters - table name and column name.

public function up()
{
  if (Schema::hasTable('flights')) {
    Schema::table('flights', function (Blueprint $table) {
      if (!Schema::hasColumn('flights', 'departure_time')) {
    $table->timestamp('departure_time');
      }
    });
  }
}

You can read more about migrations and its various features in the official documentation.

Enjoyed This Tutorial?

Get access to all premium tutorials, video and text courses, and exclusive Laravel resources. Join our community of 10,000+ developers.

Comments & Discussion

No comments yet…