How to get database field type in Laravel?

后端 未结 9 2089
离开以前
离开以前 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:28

    Within the model: laravel5.x

        $temp = $this->newQuery()->fromQuery("SHOW FIELDS FROM ".$this->getTable());
    
        foreach($temp as $val){
           echo 'Field: '.$val->Field;
           echo 'Type: '.$val->Type;
       }
    
    0 讨论(0)
  • 2020-12-14 02:38

    Generalizing:

    DB::connection()->getDoctrineColumn($tableName, $colName)
        ->getType()
        ->getName();
    

    It works on Laravel 5.3.

    0 讨论(0)
  • 2020-12-14 02:39

    For Laravel 5.2 - 7.x

    use Illuminate\Database\Schema\Builder::getColumnType()

    DB::getSchemaBuilder()->getColumnType($tableName, $colName)
    

    e.g.

    DB::getSchemaBuilder()->getColumnType('user', 'age')
    

    You may need to run

    composer require doctrine/dbal
    

    if you haven't already.

    0 讨论(0)
提交回复
热议问题