OK, we figured hopefully we'd hopefully save at least one other person at some point the hours we spent digging into this. This isn't the end all - be all, but it should be enough to give you a pretty good idea of what is needed for something like this in a bit more detail. We're using mostly methods from the ColumnDefininition class.
We have the fields hard-coded here, but in the real world they are pulled from the DB. If you comment out the die and dump below and your DB is setup, you should see the table matches 100%. If you don't want to actually create it, just look at the dd() output. Hope this helps someone some day,
public function createDynamic($table_name = 'test', $timestamps = true)
{
$fields = [
['name' => 'id', 'type' => 'increments', 'size' => null, 'index' => null, 'nullable' => 0, 'unsigned' => 0, 'default' => null],
['name' => 'field_1', 'type' => 'string', 'size' => 300, 'index' => null, 'nullable' => 0, 'unsigned' => 0, 'default' => null],
['name' => 'field_2', 'type' => 'string', 'size' => null, 'index' => 'unique', 'nullable' => 1, 'unsigned' => 0, 'default' => null],
['name' => 'field_3', 'type' => 'integer', 'size' => null, 'index' => null, 'nullable' => 0, 'unsigned' => 1, 'default' => null],
['name' => 'field_4', 'type' => 'integer', 'size' => null, 'index' => null, 'nullable' => 0, 'unsigned' => 0, 'default' => 123]
];
Schema::create($table_name, function (Blueprint $table) use($fields, $timestamps){
if (count($fields) > 0) {
$cnt = 0;
foreach ($fields as $field) {
if($field['size'] > 0) {
$table->{$field['type']}($field['name'], $field['size']);
} else {
$table->{$field['type']}($field['name']);
}
if($field['nullable'] > 0) {
$table->getColumns()[$cnt]->nullable();
}
if($field['unsigned'] > 0) {
$table->getColumns()[$cnt]->unsigned();
}
if(strlen($field['default']) > 0) {
$table->getColumns()[$cnt]->default($field['default']);
}
if(strlen($field['index']) > 0) {
switch ($field['index']) {
case 'unique':
$table->getColumns()[$cnt]->unique();
break;
case 'index':
$table->getColumns()[$cnt]->index();
break;
case 'primary':
$table->getColumns()[$cnt]->primary();
break;
}
}
$cnt++;
}
}
if($timestamps) {
$table->timestamps();
}
dd($table);
});
}