55

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 ?

Pankaj
  • 9,749
  • 32
  • 139
  • 283
  • Are you even using laravels built-in migration tool? – Morten Feb 17 '16 at 21:11
  • yes, 5.2.15 version. – Pankaj Feb 17 '16 at 21:16
  • And you run `php artisan migrate` ? If the file was run successfully, it should store that in the database so it won't run the file again – Morten Feb 17 '16 at 21:20
  • I am using `php artisan migrate:refresh` and next time, it tries to rerun the old scripts. – Pankaj Feb 17 '16 at 21:21
  • Try without `:refresh` – Morten Feb 17 '16 at 21:23
  • same issue when i ran this: `php artisan migrate` – Pankaj Feb 17 '16 at 21:25
  • No errors? (except trying to create a table that already exists) Is your migration table populated with the filenames of which it tries to run? If you try it on a new database, will it succeed without any errors, and therefore populate the migrations table with successfull migrated files? – Morten Feb 17 '16 at 21:37

3 Answers3

104

Try this for create table if doesn't exist

use Illuminate\Support\Facades\Schema;

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();
    });
}
Community
  • 1
  • 1
paranoid
  • 6,799
  • 19
  • 49
  • 86
6

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.

Community
  • 1
  • 1
Brn.Rajoriya
  • 1,534
  • 2
  • 23
  • 35
1
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

Hexxefir
  • 1,600
  • 1
  • 8
  • 9