Home > Software design >  How to run migrations even if the table already exist?
How to run migrations even if the table already exist?

Time:02-24

I ran php artisan migrate:fresh to delete every table, then I have a sql dump file that also creates the tables and populates them with some data. However then I also need to run php artisan migrate since there are some migrations that are needed to add some extra columns to some tables (and these columns are not in the sql dump file I'm using).

So, I run php artisan migrate I'm always getting some errors like this:

SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'categories' already exists (SQL: create table `categories` (`id` bigint unsigned not null auto_increment primary key, `title` varchar(255) not null, `description` varchar(255) not null, `is_active` tinyint(1) not null, `created_at` timestamp null, `updated_at` timestamp null) default character set utf8mb4 collate 'utf8mb4_unicode_ci')

In fact the table already exist but there are some other migrations that are necessary to run besides this one to create the categories table. There is some way to ignore this error or something like that so the other migrations that didnt the job yet can be executed?

CodePudding user response:

Check if the table already exists:

if (Schema::hasTable('categories')) {
   // The "categories" table exists...
}

If you want to alter the table, you can add columns or edit existing ones. Check out column modifiers https://laravel.com/docs/9.x/migrations#column-modifiers

CodePudding user response:

There can be 2 ways to do it. 1. Comment the code inside the create table migration. It will skip that help run all others. 2. There is a table in DB named migrations, make sure that migration is already in the table.

CodePudding user response:

If you would like to remove everything in your table to perform what is called a fresh migration, you can run the following code in your terminal:

php artisan migrate:fresh

Be warned, once more, running this command will DELETE every single table, column, row, and cell in your table, so it is only logical to perform in development before you start the process of making alter migrations.

the create_categories_table doesnt appear on the migrations table but so do you know why its showing that error that already exists?

Try deleting everything cached just to be sure that nothing has been cached, but I'm not entirely sure that the migration process can be fixed this way. It really doesn't hurt to try the following line:

php artisan optimize:clear
  • Related