How to fetch the tables list in database in Laravel 5.1

I need to list out the tables in database, I found this query

SHOW TABLES LIKE  'merTrans%'

to get the tables but how could I use the foreach to get the table names in Laravel 5.1?


Solution 1:

To list out the tables in database you can do

$tables = DB::select('SHOW TABLES');
foreach($tables as $table)
{
      echo $table->Tables_in_db_name;
}

You'll have to change the db_name to the name of your database.

EDIT : FOR LIKE CASES

foreach ($tables as $table) {
    foreach ($table as $key => $value)
        echo $value;
}

Solution 2:

I've been using this:

$tables = DB::connection()->getDoctrineSchemaManager()->listTableNames();

It requires doctrine/dbal as a dependency. But some migration features already need DBAL to work.

Solution 3:

To get a quick array containing all databases you can use the following piece of code:

// Iterate over the results of SHOW TABLES
// strip off all the objects and keys.
$tables = array_map('reset', \DB::select('SHOW TABLES'));

To me this seems to be the most elegant solution.

Solution 4:

For Postgres Users:

SHOW TABLES is not supported so you have to do something a bit more hackey.

$tables = DB::select("SELECT table_schema,table_name, table_catalog FROM information_schema.tables WHERE table_catalog = 'YOUR TABLE CATALOG HERE' AND table_type = 'BASE TABLE' AND table_schema = 'public' ORDER BY table_name;")

Make sure you fill out table_catalog (which I guess is equatable to database). You may have to tweak your results a bit.