Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel won't let me migrate a table because it already exists

I am trying to use Laravel Migration to create SQL tables but it won't let me.

Here is the error:

SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'mytable' already exists

Here is my code:

        Schema::create('mytable', function (Blueprint $table) {
            $table->increments('id');
            $table->foreign('othertable_id')
                ->references('id')->on('othertable')
                ->onDelete('cascade');
            $table->string('variable');
            $table->timestamps();
    });

    }

    {
        Schema::drop('mytable');
    }

I have also checked if other migrations are called "mytable" but they are not, so I am not sure where this come from.

I tried the following:

First

php artisan migrate:refresh

Which gave me an error

And then I deleted the entire database altogheter and used:

php artisan migrate

And still got the error

like image 893
prgrm Avatar asked Apr 03 '17 13:04

prgrm


2 Answers

In laravel 5.5 and > you can use:

  $ php artisan migrate:fresh 
  // ( not migrate:refresh wich is a different command)

This command first drops all tables and then reruns all migrations

like image 190
Mister Verleg Avatar answered Nov 15 '22 07:11

Mister Verleg


If you have the table in DB and dont want migrate create it, you can ignore it by check Schema::hasTable before create

public function up()
{
    if(Schema::hasTable('products')) return;       //add this line to migration file
    Schema::create('products', function (Blueprint $table) {
    $table->increments('id');
    $table->timestamps();
});

}

like image 23
Mohsen Avatar answered Nov 15 '22 06:11

Mohsen