Check table or column exists in database in Laravel

While working on an enterprise-level project, it commonly occurs that we want to create a particular table or column into a table that already exists and that shows an error. In this tutorial, we will see how to check particular table or column exists or not.

Typical migration looks like below code:

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

When we run the migration command then it will show an error if the posts table is already created. But if we add Schema::hasTable() method to the migration file then we can check particular table exists in the database or not. Based on the condition result we can decide further operation.

Let’s add a condition into an up method to check table exists or not. Modify the migration file as below:

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

While the above code execution of the migration file, first of all, we will check table exists or not. If a table doesn’t exist then it will create it otherwise it will skip execution.

To check column exists in a table or not, there is another method called Schema::hasColumn(). The hasColumn() method required 2 parameters. The first one is the table name and the second one is the column name.

Let’s use hasColumn() method with the example:

public function up()
{
    if (Schema::hasTable('posts')) {
        Schema::table('posts', function (Blueprint $table) {
            if (!Schema::hasColumn('posts', 'user_id')) {
                $table->increments('user_id');
            }
        });
    }
}

In this example, first of all, it will check posts table exists or not then it will check post table has a user_id column or not. If a column is not found in the posts table then it will add a new column to that table.

Conclusion

In this article, We have used Schema Facade’s hasTable() and hasColumn() methods to check table or column exists or not in the database. You can use that method in any other place like in the controller or helpers too.