Skip to content
Advertisement

Get column type from schema in Laravel 8

I’m getting some columns from various tables within my project and would look to obtain some additional information other than the column name, I’d like to get the column type as well.

I’m usign the Schema::getColumnListing() method and am passing a table into it, I’m able to get the fields, but not the types?

My code returns a list of tables, and columns along with an isChecked state, for purposes at a later stage.

foreach ($tables as $table => $data) {
  $cols = Schema::getColumnListing($table);
  $colsWithFields = [];

  foreach ($cols as $key => $column) {
    array_push($colsWithFields, [
      'field' => $column,
      'type' => '', // somehow get type??
      'isChecked' => false
    ]);
  }

  $tables[$table]['isChecked'] = false;
  array_push($tables[$table]['columns'], $colsWithFields);
}

I did see that there’s a getType() method if I use getDoctrineColumn

Advertisement

Answer

You can use getColumnType from IlluminateSupportFacadesSchema class which takes table name and column name as input

As per your code it would look like

array_push($colsWithFields, [
  'field' => $column,
  'type' => Schema::getColumnType($table,$column),
  'isChecked' => false
]);
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement