Quick fix for Laravel migration 'table / column already exist' errors

I will say straight up that this is a quick fix to a problem that ideally you shouldn’t create for yourself, and if you have then you aren’t using Laravel migrations correctly.  This is all true, yet still I wanted to share this for those occasional emergencies.

The scenario
You’ve copied all the tables from one install of your Laravel application to another install.   On the destination install you want to add a new table or modify an existing one, so you create a new laravel migration file with the standard php artisan make:migration migrationName syntax.

However when you run php artisan migrate instead of it working you get lots of colourful errors on screen due to some of the tables or columns that the migration tool is trying to create already existing.

What’s happened?
Basically the migrations table in your app is out of date and doesn’t contain all the entries it should.  Because it doesn’t contain some entries the migration tool runs over various historical migration files that it believes need to be executed, however in reality they’ve already been run and the resulting tables already exist.   So all the commands in the migration files that are not referenced in the migrations table will attempt to be executed even though they don’t need to be.

If you google these problems online the solution normally given (and in theory the correct one) is to rollback the migrations and resolve the issue that way.   That’s fine and a good way to resolve the issue, but what if you really want the data inside the tables of your app and don’t want to loose that and fiddle around with possible further rollback complications?

The quick solution - where my migration fixer comes in handy!

The quick fix is to create new entries in the migrations table so that all historical migration files found in your /database/migrations folder are added to the migrations table.      

That’s fine if there are just a couple of migrations to add, you can do it manually.  However what if there is a significant number?  It’s a real pain and that’s where this quick and dirty tool comes in handy and attempts to resolve.

Usage Steps
1) Backup your entire app database - I won’t be held responsible for any data loss!
3) copy the file to the root of your Laravel install (not inside the app folder)
4) rename the extension, changing .txt for .php
5) check that your database is setup using the standard conventions of the .env file
6) run php migration-table-fixer.php

This is coded using mysqli PHP functionality so there is an assumption that your tables are in mySQL / MariaDB.

Good luck and I hope it’s useful to someone!  

Last Updated: 20/8/2020