ChatGPT解决这个技术问题 Extra ChatGPT

Laravel Migration table already exists, but I want to add new not the older

I previously created users table. Now I have created a new migration to create a new books table inside my schema. When I try to run the command

php artisan migrate

It shows:

[Illuminate\Database\QueryException]
SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'users' alre
ady exists (SQL: create table `users` (`id` int unsigned not null auto_incr
ement primary key, `username` varchar(255) not null, `email` varchar(255) n
ot null, `password` varchar(255) not null, `created_at` timestamp default 0
 not null, `updated_at` timestamp default 0 not null) default character set
 utf8 collate utf8_unicode_ci)

Here is my new migration table:

<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateBooksTable extends Migration {
    public function up()
    {
        Schema::create('books', function(Blueprint $table)
        {
            $table->increments('id');
            $table->string('name');
            $table->string('auther');
            $table->string('area');
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::drop('books');
    }
}

How can I get rid of the error?


C
Chuck Le Butt

In v5.x, you might still face the problem. So, try to delete related table manually first using

php artisan tinker

Then

Schema::drop('books')

(and exit with q)

Now, you can successfully php artisan migrate:rollback and php artisan migrate.

If this happens repeatedly you should check that the down() method in your migration is showing the right table name. (Can be a gotcha if you've changed your table names.)


This help me out! I got error when run users table migration-"Specified key was too long; max key length is 767 bytes" But i ignored it and continued.
Worked for me. Thanks so much.
This definitely worked for me with v5.4. @Fawel that is a completely different problem. Here is a link to what you need to fix that Laravel 5.4: Specified key was too long error.
@UsamaMunir Glad to hear that. You can always use phpmyadmin or table plus to dump migrations table there. Or use the great database connection extensions in your IDE.
e
eatingthenight

You need to run

php artisan migrate:rollback

if that also fails just go in and drop all the tables which you may have to do as it seems your migration table is messed up or your user table when you ran a previous rollback did not drop the table.

EDIT:

The reason this happens is that you ran a rollback previously and it had some error in the code or did not drop the table. This still however messes up the laravel migration table and as far as it's concerned you now have no record of pushing the user table up. The user table does already exist however and this error is throw.


Yeah thanks. But I want to know why does it messed up?
Well put that in your question then you asked how you can get rid of it and I answered that question. Sorry that I am unable to read your mind.
sorry for the comment as you thought. I have did that as you said. It works. I thought it would work. However, can you please tell me the reason behind this error? Thanks :)
@MD.AtiqurRahman The reason why it was messed up -- If I'm guessing right -- is that you have created a migration twice.
for me say 'php artisan migrate:rollback'
A
Abaza

I had the same trouble. The reason is that your file name in migrations folder does not match with name of migration in your database (see migrations table). They should be the same.


Oh Man ! That a long ago !
this is not always the case as laravel when i was using it anyway would fail migrations all the time when you were messing around with them causing it to make changes or rollback changes and not update the database.
Agreed w/ @mschuett -- I got such an error just following the Laravel 5.2 'quickstart' instructions. I even cleaned everything out, started a whole new project, and it happened again.
Thanks , you save lot of my time. After i check my database, suddenly my migrate is empty, but remain only table exist. so i need to delete it manual. thanks
@Abaza thx i had the same problem and indeed i changed the name of a table and also edited it on the filename but not in the migration stable.
v
vinkomlacic

You can use php artisan migrate:fresh to drop all tables and migrate then. Hope it helps


This answer should be upvoted more.You may be familiar with the migrate:refresh command that allows you to rollback and re-runs all of your migrations. This helps when you need to rebuild your database during development. Coming to Laravel 5.5 is an improvement on this with a new command named migrate:fresh. The difference between “refresh” and “fresh” is that the new fresh command skips all the down methods or the rollback by dropping the tables, then running through the up methods.
This is not correct! This will drop all tables in your schema!
@levan it's stated above that it drops all tables. I suggested it as a solution if dropping all tables is an option.
in my case it doesn't work because i have 2 databases , for some reason it throws the error Base table or view already exists: 1050 Table 'users' already exists . It seems the second database is not being reset .
Thank you this solutions works on heroku
T
Trikly

Also u may insert befor Schema::create('books', function(Blueprint $table) the following code Schema::drop('books');


or try this one : Schema::dropIfExists('books');
m
maksbd19

EDIT: (for laravel)

Just Came across this issue while working on a project in laravel. My tables were messed up, needed to frequent changes on columns. Once the tables were there I wasn't able to run php artisan migrate anymore.

I've done following to get rid of the issue-

Drop the tables in the database [every one, including the migration table] $ composer dump-autoload -o php artisan migrate

Previous Comment, regarding lumen

[Well, pretty late to the party (and possibly a different party than what I was looking for). I banged my head, screamed out loud and by the grace of gray skull just found a solution.]

I'm developing an restful app using lumen and I'm new to it. This is my first project/experiment using laraval and lumen. My dependencies-

"require": {
    "php": ">=5.6.4",
    "laravel/lumen-framework": "5.4.*",
    "vlucas/phpdotenv": "~2.2",
    "barryvdh/laravel-cors": "^0.8.6",
    "league/fractal": "^0.13.0"
},
"require-dev": {
    "fzaninotto/faker": "~1.4",
    "phpunit/phpunit": "~5.0",
    "mockery/mockery": "~0.9.4"
}

Anyway, everything was fine until yesterday night but suddenly phpunit started complaining about an already existed table.

Caused by
PDOException: SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'items' already exists

Duh! Items table should exist in the database, or else how am i supposed to save items!

Anyway the problem only persisted in the test classes, but strangely not in the browser (I checked with chrome, firefox and postman altering headers). I was getting JSON responses with data as expected.

I dropped the database and recreated it with lots of migrate, refresh, rollback. Everything was fine but in phpunit.

Out of desperation I removed my migration files (of course I took a backup first ) then hit phpunit in the terminal. Same thing all over again.

Suddenly I remembered that I put a different database name in the phpunit.xml file for testing purpose only. I checked that database and guess what! There was a table named items. I removed this table manually, run phpunit, everything started working just fine.

I'm documenting my experience for future references only and with hope this might help someone in future.


N
Nik K

I inherited some real bad code from someone who wasn't using migrations!?, so manually pasted the filenames into the migrations, forgetting to remove the trailing .php

So that caused the 'table exists' error despite the filename and migration matching.

2018_05_07_142737_create_users_table.php - WRONG 2018_05_07_142737_create_users_table - CORRECT


Solved my issue too
M
Murad

You can delete all the tables but it will be not a good practice, instead try this command

php artisan migrate:fresh

Make sure to use the naming convention correctly. I have tested this in version laravel 5.7 It is important to not try this command when your site is on server because it drops all information.


Worked for me :)
M
Martijn van der Bruggen

I had a similar problem after messing with foreign key constraints. One of my tables (notes) was gone and one kept coming back (tasks) even after dropping it in MySQL, preventing me from running: php artisan migrate/refresh/reset, which produced the above 42s01 exception.

What I did to solve it was ssh into vagrant then go into MySQL (vagrant ssh, mysql -u homestead -p secret), then: DROP DATABASE homestead; Then CREATE DATABASE homestead; Then exit mysql and run:php artisan migrate`.

Obviously this solution will not work for people not using vagrant/homestead. Not claiming in any way this is a proper workflow but it solved my problem which looks a lot like the above one.


g
goto

you drop all tabel in your database, then

https://i.stack.imgur.com/xchYR.png

php artisan migrate:refresh

edit your migration file

php artisan migrate:rollback

php artisan migrate again ^_^

done your table !!


V
Vim Diesel

DANGER - most of these answers will wipe your database and is not recommended for production use.

It's clear there are a lot of "solutions" for this problem, but all these solutions I read through are very destructive solutions and none of them work for a production database. Based on the number of solutions, it also seems that there could be several causes to this error.

My error was being caused by a missing entry in my migrations table. I'm not sure exactly how it happened but by adding it back in I no longer received the error.


Although it's not the best practice, for emergencies I occasionally create the entries missing in the migrations table manually. For scenarios where lots of entries need adding into the migrations table I made a tool for this: adam-makes-websites.com/discoveries/…
A
Aydın Bulut

I think my answer will help more. I faced this error also. Then I deleted specific migration file and tried to recreate by php artisan.

But before get this point 1 or 2 days ago while I was watching laracast videos about migation, I was thinking rollback and migrate specific table. For some reason I deleted specific migration file and tried recreate but doing so I got:

[ErrorException] include(C:\wamp64\www\laraveldeneme\vendor\composer/../../database/migrations/2017_01_09_082715_create_articles_table.php): failed to open stream: No such file or directory

When I check that file I saw the line below at top of array in the autoload_classmap.php file:

'CreateArticlesTable'=>$baseDir.'/database/migrations/2017_01_09_083946_create_articles_table.php',

Altough rollback or delete a migration file, the record related with the migration file remains in the composer autoload_classmap.php file.

To solve this problem, I have found composer command below from somewhere I can't remember.

composer dump-autoload

When I rand this code, the line related with the migration file that I deleted is gone. Then I ran:

php artisan make:migration create_articles_table --create=articles

Finally I recreated my migration file with same name


S
Silvanas

go to phpmyadmin and drop the database that you created for laravel then create it again then go to cmd(if use windows) root project and type php artisan migrate


That is not the answer. Why not using cmd to drop the table or rolling back?
because it's not working for some device in first try and told to us nothing to roll back
C
Cengkuru Michael

You can always check for a table existence before creating it.

    if(!Schema::hasTable('books')){
 Schema::create('books', function(Blueprint $table)
        {
            $table->increments('id');
            $table->string('name');
            $table->string('auther');
            $table->string('area');
            $table->timestamps();
        });
}

f
flik
php artisan migrate:rollback 

Check solution: Laravel Official Solution

As outlined in the Migrations guide to fix this all you have to do is edit your app\Providers\AppServiceProvider.php file and inside the boot method set a default string length:

use Illuminate\Support\Facades\Schema;

public function boot()
{
    Schema::defaultStringLength(191);
}

After above command you need to delete all remaining tables manually and then run the command:

php artisan migrate:fresh

J
James

For anybody still looking for an answer, if the migration is stuck at trying to run one of the migrations that have already been run (hence, the "Table already exists" problem) simply do the following:

Open the PHP file for the table causing the issue and comment out all the code in the "up()" function.

Run "php artisan migrate" again. The file/table causing the problem will process with it's empty function.

The migration will then move on to your new waiting migrations. Once done, uncomment the lines previously commented out (optional but recommended so as not to confuse other developers)


C
Community

After rollback check your tables , be sure of deletion.

If there is a problem delete tables manually from database application like phpmyadmin ( I'm using sequel pro for mac ).

Correct your down methods in the migration .

Note : Do rollback then migrate .. Don't use migrate:refresh to notice where is the error been .

After that you may test with new db for testing. to detect where is the problem.

Also try reading this question


n
ntsasng

Add this to AppServiceProvider.php

use Illuminate\Support\Facades\Schema;
public function boot() {
    Schema::defaultStringLength(191);
}

J
Jacksonit.org

Drop all table database Update two file in folder database/migrations/: 2014_10_12_000000_create_users_table.php, 2014_10_12_100000_create_password_resets_table.php

2014_10_12_100000_create_password_resets_table.php

Schema::create('password_resets', function (Blueprint $table) {
     $table->string('email');
     $table->string('token');
     $table->timestamp('created_at')->nullable();
});

2014_10_12_000000_create_users_table.php

Schema::create('users', function (Blueprint $table) {
     $table->increments('id');
     $table->string('name');
     $table->string('email');
     $table->string('password');
     $table->rememberToken();
     $table->timestamps();
});

A
Andrew Lohr

I solved your problem by deleting the "user" table in sequel-pro (there is no data in my user table) and then you can run php artisan migrate

Here are before and after screen shots

before I delete the user table user

https://i.stack.imgur.com/O0YLa.png

https://i.stack.imgur.com/z6PmY.png


U
Udhav Sarvaiya

Drop all tables manually at the phpmyadmin. Go to each migration file at database/migrations. Find and remove these 2 codes : a) ->index() (found at 2014_10_12_100000_create_password_resets_table.php at line 17) b) ->unique() (found at 2014_10_12_000000_create_users_table.php at line 19) Run php artisan migrate Done.

I think this happens because the latest laravel class (at 12th February 2018) has removed the function of ->index() and ->unique()


R
Riki krismawan

very annoying if we have to delete a table that failed to make. so I use dropIfExists('table_name') function to delete a table if has table before creating a new table

Schema::dropIfExists('books');
Schema::create('books', function(Blueprint $table)
{
   $table->increments('id');
   $table->string('name');
   $table->string('auther');
   $table->string('area');
   $table->timestamps();

});

S
Stubbies

First drop the users table in the database.Then go to command propmt and type

php artisan migrate

all sets.I think this answer helps.


Are you sure it's "artsian" and not "artisan"?
S
Sameera Liyanage

In laravel 5.4, If you are having this issue. Check this link

-or-

Go to this page in app/Providers/AppServiceProvider.php and add code down below

use Illuminate\Support\Facades\Schema;

public function boot()
{
Schema::defaultStringLength(191);
}

F
Francesco Boi

I also had this issue, just came across this answer on a Youtube Video. Not sure if it's ideal, but it's the best I've seen.

Seems the AppServiceProvider.php file of the providers directory by giving the Schema a length. In this case 191. Works like magic.Screenshot. He then ran: php artisan migrate:fresh. Hope this works.


M
Masoud Rezaei

First check the migrations table in your DB and sure that your migration files in database folder in your project is equal to this table data. Sometimes if you create migration files by manual appear this error when run migrate command in composer.


M
Mehemmed

Solution :Laravel Migration table already exists... || It Works in Laravel 5.8 also

app\Providers\AppServiceProvider.php file

and inside the boot method set a default string length:

public function boot()
{
    Schema::defaultStringLength(191);
}

and open

config\database.php

'charset' =>'utf8mb4',
'collation' =>'utf8mb4_unicode_ci',

and change it to

'charset' =>'utf8',
'collation' =>'utf8_unicode_ci',

save all the files and go to command prompt

php artisan migrate

R
Risheekant Vishwakarma

Answer is very straight forward :

First take a backup of folder bootstrap/cache.

Then delete all the files from bootstrap/cache folder .

Now run:

php artisan migrate 

U
Udhav Sarvaiya

Creating a database literally takes seconds.

Export your current database in case it has sensitive data.

Check your migrations and eliminate all wrong methods in it.

Drop database and Re-create database.

php artisan migrate

Then you can return the data previously in the database.


U
Udhav Sarvaiya

I was also facing the same problem, I followed the same process but my problem was not resolving so I try another thing. I dropped the tables from my database and use a header file

use Illuminate\Support\Facades\Schema;

and increase the default string length in boot method to add this:

Schema::defaultStringLength(191);

then again php artisan migrate. Problem is resolved, all tables are created in the database.


关注公众号,不定期副业成功案例分享
Follow WeChat

Success story sharing

Want to stay one step ahead of the latest teleworks?

Subscribe Now