7

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)|
ajreal
  • 46,720
  • 11
  • 89
  • 119
Qazi
  • 5,015
  • 8
  • 42
  • 62
  • Possible repetition: http://stackoverflow.com/questions/19951787/laravel-4-get-column-names – Amarnasan Oct 23 '15 at 08:01
  • I am not getting my desire results, I got the columns name but not Type and its length – Qazi Oct 23 '15 at 08:07
  • Ok, then look here... http://stackoverflow.com/questions/18562684/how-to-get-database-field-type-in-laravel (did you made any research effort?) – Amarnasan Oct 23 '15 at 08:10
  • Yes, I am doing my research, – Qazi Oct 23 '15 at 09:39
  • Doing your research doesn't mean asking people on SO about something you can find on your own in 5 minutes.. – Mjh Oct 23 '15 at 09:59

3 Answers3

3

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;
}
Jeremy
  • 3,620
  • 9
  • 43
  • 75
2

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 :)

Vandolph Reyes
  • 622
  • 6
  • 18
0

One thing I've added to my larger models at the beginning of projects is a handy static function which returns all table columns data as an array so it can be used with Tinker or otherwise:

public static function describe()
{
    return DB::select(DB::raw("DESCRIBE " . (new self)->getTable(). ";"));
}

Then call this in tinker or otherwise with App\Models\ModelName::describe()

Tyson L.
  • 53
  • 9
  • The first comment on the question links to a similar question and its accepted answer provides a *Laravel* specific method. Note that your answer is database-driver specific as with one of the other answers. The Laravel documentation has this resource https://laravel.com/api/5.8/Illuminate/Database/Schema/Builder.html#method_getColumnListing providing `getColumnListing(string $table)`. – Supernovah Apr 26 '20 at 04:30