While working on an enterprise-level project, it commonly occurs that we want to create a particular table or column into a table which 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 into migration file then we can check particular table exists in database or not. Based on the condition result we can deside further operation.
Let's add a condition into an up method to check table exists or not. Modify 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 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 exist in table or not, there is another method called Schema::hasColumn(). The hasColumn() method required 2 parameters. The first one is the table name and second one is the column name.
Let's use hasColumn() method with 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 user_id column or not. If a column is not found in the posts table then it will add new column to that table.
In this article, We have used Schema Facade's hasTable() and hasColumn() method to check table or column exist or not in database. You can use that method in any other place like in controller or helpers too.
Ask anything about this examples