laravel schema builder, find columnType autoincrement

408 Views Asked by At

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();
                });
            }
        }
1

There are 1 best solutions below

1
On BEST ANSWER

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:

0 => {#162 ▼
    +"Field": "id"
    +"Type": "int(11)"
    +"Null": "NO"
    +"Key": "PRI"
    +"Default": null
    +"Extra": "auto_increment"
  }

1 => {#164 ▼
    +"Field": "name"
    +"Type": "varchar(255)"
    +"Null": "YES"
    +"Key": ""
    +"Default": null
    +"Extra": ""
  }

Now you can easily extract the "Extra" : "auto_increment" , like this:

$result = DB::select("SHOW COLUMNS FROM product");
foreach ($result as $key => $value) {
            if($value->Extra == 'auto_increment'){
                //do something
            };