Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel: How to get table column name, its type and length

Is there any method available in Laravel 5/5.1, through which we can get the Table columns name, its type and length, Means table meta data?

eg:

Name    |    Type    |    Length

ID      |    Integer |    11
Name    |    varchar |    100
Email   |    varchar |    100
Password|    md5     |    82
Address |    tinytext|    
DOB     |    date    |    
Status  |    enum(0,1)|
like image 475
Qazi Avatar asked Oct 23 '15 07:10

Qazi


2 Answers

I attempted this but kept getting PDO errors because not all drivers are supported. So if you use MySQL or MariaDB this may help.

$columns = DB::select( DB::raw('SHOW COLUMNS FROM `'.$table.'`'));

foreach($columns as $column) {
    $name = $column->Name;
    $type = $column->Type;
}
like image 162
Jeremy Avatar answered Sep 29 '22 05:09

Jeremy


You can check it here. https://laravel.com/api/5.1/Illuminate/Database/Connection.html

Sample code for getting type of password field from users table.

dd(DB::connection()->getDoctrineColumn('users', 'password')->getType()->getName());

I'll leave the rest to you. Goodluck :)

like image 35
Vandolph Reyes Avatar answered Sep 29 '22 05:09

Vandolph Reyes