I'm working to update an existing database to use autoincremented primary keys. This DB currently has crazy named PK fields with custom values. I need to check each table first to see if it HAS an autoinc field first, then I want to drop it and replace with 'id' field.
I want to do this as a migration, here's what I have so far but I can't seem to identify if the first col is autoincrementing already so I can drop the existing PK and replace. I need to replace the hasColumn with something like a firstColumn then getColumnType...
foreach ($tableNames as $name)
if (!Schema::hasColumn($name, 'id')) {
Schema::table($name, function ($table) {
$table->dropPrimary();
$table->increments('id')->first();
});
}
}
In order to solve the problem I ran the following code from a controller. Notice here that I have only two fields for the demo (
id
,name
)$result = DB::select("SHOW COLUMNS FROM table_name"); dd($result);
Now the output after
dd()
will be somewhat like this:Now you can easily extract the
"Extra" : "auto_increment"
, like this: