Laravel Migrations: Check if Table/Column Already Exists



In this post, I explain how to check Table/Column already exist or not in Laravel.

When we working on a big project generally we faced migration for the same table or even column that already exists. Luckily, Laravel has a quick way of checking it. 

Typical migration file looks like this:

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

ok, Suppose if flights table already exists in our database, you would get an error. The 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();
    });
  }
}

By using this migration method, if table flights do not exist, then we create it.

if we want to add a new column to the existing table, then we may check if the 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.

So here we completed post on Laravel Migrations: Check if Table/Column Already Exists


About Author
  • user profile
    Brijpal Sharma

    brijpalsharma99@gmail.com, January 29th, 2018

    Hi, I am a web developer, I working on Laravel and CodeIgniter framework, I love to share knowledge and tutorials so I here...


0 Comment


You must be logged in to post a comment.


You may also be interested in...
jQuery plugin to validate the maximum length of the field and count characters.
Deploy Laravel Application To Shared Hosting The Easy and save Way
Laravel advance search filters with optional fields.
Laravel Migrations: Check if Table/Column Already Exists
Connect Multiple databases in the same Laravel project
SEO tool for Laravel Application
Paypal payment gateway integration in Laravel 5.7 step by step
How to Check User online or not in Laravel
How to keep filter data after the click to next button in Laravel pagination
Which is better for web development, Laravel or Flask?