Home » Php » php – Schema Builder : Create Table if not exists

php – Schema Builder : Create Table if not exists

Posted by: admin April 23, 2020 Leave a comment

Questions:

I am using below code in Schema Builder to create table.

Schema::create('tblCategory', function (Blueprint $table) {
    $table->increments('CategoryID');
    $table->string('Category', 40);
    $table->unique('Category', 'tblCategory_UK_Category');
    $table->timestamps();
});

Here is the problem is, if I have to create the new table, all old scripts runs and show error that table already exists.

is there any way to create table if not exists using Schema builder ?

How to&Answers:

Try this

if (!Schema::hasTable('tblCategory')) {
     Schema::create('tblCategory', function($table){
            $table->engine = 'InnoDB';
            $table->increments('CategoryID');
            $table->string('Category', 40);
            $table->unique('Category', 'tblCategory_UK_Category');
            $table->timestamps();
    }
}

Answer:

Please check the answer here

To create a new table there is only one check by Laravel Schema function hasTable.

But if you want to drop any table before checking its existence then Schema have a function called dropIfExists.

Schema::dropIfExists('table_name');

It will drop the table if table will exist.

Answer:

DB::transaction(function () {
        // Create your table here with schema builder.
});

If an exception is thrown within the transaction Closure, the transaction will automatically be rolled back. So trying to create a table already existing will throw an error. Most database transactions should have this closure in Laravel.

https://laravel.com/docs/5.6/database