Skip to content
Advertisement

How to run migrations even if the table already exist?

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?

Advertisement

Answer

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

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement