How to get database field type in Laravel?

后端 未结 9 2141
离开以前
离开以前 2020-12-14 01:38

Is there a way to get the datatype of a database table field? Almost like a inverse of migration.

For example, if the migration of a users table column looks like

9条回答
  •  没有蜡笔的小新
    2020-12-14 02:13

    In Laravel 5+ (including 6 and 7), you can get the db table column metadata (ie type, default value etc) in the following way:

    use Illuminate\Support\Facades\Schema;
    

    For all columns:

     $columns = Schema::getConnection()->getDoctrineSchemaManager()->listTableColumns('table_name');
     $column = Schema::getConnection()->getDoctrineColumn('table_name'', 'column_name'); //For a single column:
    

    getDoctrineSchemaManager method returns a array of \Doctrine\DBAL\Schema\Column Class Instances.

    getDoctrineColumn method returns the instance of \Doctrine\DBAL\Schema\Column class.

    Couple of methods from \Doctrine\DBAL\Schema\Column class:

    $column->getName();
    $column->getNotnull(); // returns true/false
    $column->getDefault(); 
    $column->getType(); 
    $column->getLength();
    

提交回复
热议问题