37

I have tried to get all column names from a table Teller

Function:

public function getTableColumns($tables)
{
    return DB::select(DB::raw('SELECT 
                                    COLUMN_NAME, 
                                    DATA_TYPE, 
                                    COLUMN_DEFAULT
                                FROM 
                                    INFORMATION_SCHEMA.COLUMNS
                                WHERE 
                                    table_name = `Teller`'));
}
Bert H
  • 1,087
  • 1
  • 15
  • 29
DMS-KH
  • 2,669
  • 8
  • 43
  • 73

14 Answers14

107

You can get all columns name by simply doing that...

use Illuminate\Support\Facades\Schema;

use Illuminate\Support\Facades\DB;

public function getTableColumns($table)
{
    return DB::getSchemaBuilder()->getColumnListing($table);

    // OR

    return Schema::getColumnListing($table);

}
Parvez Rahaman
  • 4,269
  • 3
  • 22
  • 39
  • The problem here when doing joins is that you need to prefix the column names with the table name like: $tableName =...; $columns = Schema::getColumnListing($tableName); $columns = array_map(function ($elem) use ($tableName) {return $tableName . '.' . $elem;}, $columns); – Alex Oct 06 '21 at 14:34
  • Excellent! It's working – Mamun Sabuj Jan 17 '22 at 08:31
25

Get Table Name From Model

$product = new Product;
$table = $product->getTable();
print_r($table);

Get Table Column Name From Model

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{   
    public function getTableColumns() {
        return $this->getConnection()->getSchemaBuilder()->getColumnListing($this->getTable());
    }
}

Now you will get all columns of "products" table and if you need it in controller then you can get it by following way :

 $product = new Product;
 $columns = $product->getTableColumns();
 print_r($columns);
Tom
  • 4,070
  • 4
  • 22
  • 50
7

Just in-case if you have multiple databases connections, try following:

Add in the top of your php script

use Illuminate\Support\Facades\Schema;

Retrieve anywhere in your code

With Database Connection

$columns = Schema::Connection('business')->getColumnListing('users'); // 'business' is your database connection

        echo "<pre>";
        print_r($columns);
        exit();

Without Database Connection

$columns = Schema::getColumnListing('users');

    echo "<pre>";
    print_r($columns);
    exit();
Muhammad Sheraz
  • 569
  • 6
  • 11
3

You only need extract the keys from the query response

array_keys(json_decode(json_encode($table[0]), true))
Nikolai Shevchenko
  • 7,083
  • 8
  • 33
  • 42
3

As of Laravel 6.x this works:

                    $db = DB::connection()->getPdo();
                    $rs = $db->query('SELECT * FROM Teller LIMIT 0');
                    for ($i = 0; $i < $rs->columnCount(); $i++) {
                            $col = $rs->getColumnMeta($i);
                            $columns[] = $col['name'];
                    }
                    print_r($columns);

The hint here is just to go around eloquent (which should just provide a simple way to do this, but clearly does not) and grab the PDO object and then use the answer from the same question for straight PDO access

This will also work when there is no database selected by replacing 'Teller' with databasename.Teller

HTH,

-ft

ftrotter
  • 3,066
  • 2
  • 38
  • 52
3

Another way from a model using collections.

collect(User::first())->keys();
PhilWilliammee
  • 541
  • 6
  • 10
2

@Eduardo Wallace method has it simplest; just return the first value from the table, strip off the values leaving the keys

$T1 = table_name::first();
$table_columns = array_keys(json_decode($T1, true));

If you don't need all the columns, strip away unneeded columns, leaving only the ones needed:

$needed_columns = array_diff($table_columns, ['unneeded_1', 'unneeded_2']);

You can argue the method used, simplest to me anyways!

DAVID AJAYI
  • 1,912
  • 20
  • 13
1
$db = [];
$tables =  DB::select('SHOW TABLES');

    foreach ($tables as $key => $table) {
        $name = $table->Tables_in_app;
        $app[$name] =  DB::getSchemaBuilder()->getColumnListing($name);
    }

return $db;
0

You can get an idea with this script

    $columns = array();
    foreach(\DB::select("SHOW COLUMNS FROM $table") as $column)
    {
       //print_r($column);
        $columns[$column->Field] = '';
    }
  
    return $columns;
toking
  • 1
  • 4
0

in 12.17.22 it's
extremely simple

$columns=Schema::getColumnListing('my_table_name');
//e.g. your table's name is 'my_table_name' or 'Teller' or   'posts'
// and then
$fetchedSet= Post::select($columns)->where('sender_id','>',100)->get();

And you are done

CodeToLife
  • 3,672
  • 2
  • 41
  • 29
0
$columns = DB::select("SHOW COLUMNS FROM table_name");

//This code will return column array as table defined in database.
return array_column($columns, 'Field');

//This code will return column array asc order of column name.
return Schema::getColumnListing('table_name');
Swatantra Kumar
  • 1,324
  • 5
  • 24
  • 32
0

this is work for me

use Illuminate\Support\Facades\DB;

getTableColumns((new Model())->getTable());    

function getTableColumns($table){
   return DB::getSchemaBuilder()->getColumnListing($table);
}
e sadeghi
  • 43
  • 4
  • This does not really answer the question. If you have a different question, you can ask it by clicking [Ask Question](https://stackoverflow.com/questions/ask). To get notified when this question gets new answers, you can [follow this question](https://meta.stackexchange.com/q/345661). Once you have enough [reputation](https://stackoverflow.com/help/whats-reputation), you can also [add a bounty](https://stackoverflow.com/help/privileges/set-bounties) to draw more attention to this question. - [From Review](/review/late-answers/34693943) – Yogendra Jul 19 '23 at 08:32
-3

You could simply write:

public function getTableColumns($tables)
{
    return DB::select(
        DB::raw('SELECT * FROM `Teller`')
    );
}

If you have a Teller model you can also use Teller::all();

Update

To get all column name you can run SHOW FIELDS Teller

codedge
  • 4,754
  • 2
  • 22
  • 38
-4

You can use this

DB::table('table_name')->get();
  • This is for getting data. The question was for getting column names, which should work even if no data is there. – ftrotter Oct 17 '19 at 03:25