54

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?

17 Answers 17

73

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.

4
  • 7
    I prefer this one because I don't have to deal with the different DB grammars.
    – onetdev
    Commented Mar 18, 2017 at 14:34
  • 4
    Worked like a charm. Awesome answer, this one should be accepted one! Commented Mar 6, 2018 at 12:21
  • 1
    A short and sweet solution to get all the table names from a database out of the box. Thanks @carlosvini
    – Safi Ahmed
    Commented May 21, 2020 at 20:36
  • 1
    thanks. i have to execute composer req doctrine/dbal first. (if not yet installed) Commented Nov 16, 2022 at 15:44
67

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;
}
4
  • without like condition it's working fine. But if i add the "LIKE 'merTrans%' " Undefined property: stdClass::$Tables_in_db_name. Commented Nov 3, 2015 at 6:00
  • 2
    Double foreach for something like this seems rather unnecessary?
    – killstreet
    Commented Jan 9, 2017 at 13:56
  • 2
    Note, this answer will only work for MySQL. OP is using MySQL based on the syntax, but this will not work, for instance, in an Sqlite3 or Postgresql database.
    – haz
    Commented Nov 20, 2018 at 4:01
  • $tableNames = collect(DB::select('SHOW TABLES'))->map(function($val) { return head($val); });
    – Tebe
    Commented Oct 7, 2022 at 22:15
35

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.

2
  • 3
    <3 this one.. #L55 Commented Sep 14, 2017 at 11:35
  • 3
    Perfect answer and the most elegant way to handle this. Thanks!
    – Mukeyii
    Commented Feb 12, 2019 at 10:28
11

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.

2
  • I would argue "SHOW TABLES" is the hack. information_schema is the standard way to do this.
    – rich remer
    Commented Sep 7, 2017 at 2:57
  • To follow the original question, LIKE condition needs to be added: AND table_name LIKE 'merTrans%' Commented Jul 1, 2018 at 10:38
7

In Laravel you can use:

$tables = DB::select('SHOW TABLES');
6
$tables = \DB::select("SHOW TABLES LIKE 'merTrans%'");
foreach ($tables as $table) {
  echo head($table);
}
2
  • 3
    Please edit your answer to include some explanation. Code-only answers do very little to educate future SO readers. Your answer is in the moderation queue for being low-quality. Commented Apr 21, 2017 at 16:26
  • It's a bit of a hack since Laravel's head helper was supposed to work with arrays and not objects, but it work because it basically calls reset on the parameter called to it... Commented Mar 12, 2019 at 13:42
6

In case you need to apply some migration changes to all tables.

In Laravel 6 Schema::getAllTables() became a public method, so you can do something like this:

$tables = array_filter(
    Schema::getAllTables(),
    static function ($table) {
        return preg_match('/some_(\d+)_table/', $table->{'Tables_in_' . env('DB_DATABASE')});
    }
);

foreach ($tables as $table ) {
    Schema::table(
        $table->{'Tables_in_' . env('DB_DATABASE')},
        static function (Blueprint $table) {
            $table->removeColumn('request_id');
        }
    );
}

That's relevant when you need to do (in my case above - remove a column) something with tables that have this naming structure: some_1_table, some_2_table, some_3_table, etc. So basically instead of DB::select('SHOW TABLES'); you can now use Schema::getAllTables().

5

Another solution will be, you do not need to use DB name. 'current' will take first column only.

function getTables()
{
    $tables = DB::select('SHOW TABLES');

    $tables = array_map('current',$tables);

    return $tables;
}
4

I use this to get all tables with columns:

$schema = collect(DB::connection()->getDoctrineSchemaManager()->listTableNames())->map(function ($item, $key) {
  return [
    'name' => $item,
    'columns' => DB::getSchemaBuilder()->getColumnListing($item)
  ];
});
2

Because I don't have the reputation to add a comment, yet, I'm posting this as an answer.

A recommendation for Bharat's LIKE CASES

foreach ($tables as $table) {
    echo array_shift(array_values($table));
}

if you don't like having a double foreach, but make sure you var_dump $table,

($tables = DB::select('SHOW TABLES');

to see exactly what you are dealing with.

1
 protected function getNamesTablesDB(){

        $database = Config::get('database.connections.mysql.database');

        $tables = DB::select('SHOW TABLES');

        $combine = "Tables_in_".$database;

        $collection = new \Illuminate\Database\Eloquent\Collection;

        foreach($tables as $table){
            $collection->put($table->$combine, $table->$combine);
        }

        return $collection; //or compact('collection'); //for combo select
    }
1
  • This answer's work for mysql. I would have upvote it if had some comments on how n why should this work. Commented Feb 22, 2021 at 8:10
1

Find the list of tables from your database in "Laravel"

        $tables_list = DB::select('SHOW TABLES');
        
        foreach($tables_listas $value)
        {
              echo $value->Tables_in_YourDatabaseName;
        }

'Tables_in_YourDatabaseName' means : for example if your database name is "test" then

echo $value->Tables_in_test;

1
public function hiddenTables()
   {
       return [
            'migrations',
            'password_resets',
       ];
   }



public function dbTables()
    {
        foreach (\Illuminate\Support\Facades\DB::select('SHOW TABLES') as $tables) {
            foreach ($tables as $table => $value)
                $db[] = $value;
        }

        return $db;
    }



public static function diffTables()
    {
        return array_diff((new self)->dbTables(), (new self)->hiddenTables());
    }
1
  • 1
    Please consider to add also some word comments why the code solves the problem, not only the code. Commented Aug 20, 2020 at 13:16
0

As an alternative you could use information_schema.tables to get list of table names.

function getTableNames($db_name, $search = ''){
        $rows = DB::select("SELECT table_name FROM information_schema.tables WHERE table_schema = '{$db_name}' AND table_name like '%{$search}%'");

        $table_names = [];
        foreach($rows as $row)
        {
            $table_names[] = $row->table_name;
        }

        return $table_names;
}

print_r(getTableName('my_db', 'merTrans'));
0

Since you cannot pass 'reset' into array_map anymore this is my solution:

$tables = array_map(fn($item) => $item->{array_keys(get_object_vars($item))[0]}, DB::select('SHOW TABLES'))
-1

For those, who like to use the query builder:

DB::table('sqlite_master')
    ->whereIn('type', [ 'table', 'view' ])
    ->where('name', 'NOT LIKE', 'sqlite_%')
    ->orderBy('1')
    ->pluck('name')
    ->all()
0
-4

Add flowing thing in your Laravel project :- In Controller file :-

 public function debate_list(){
         $records = DB::table('table_name')->get();
        return view('page_link')->with('records',$records);
    }

In page_link.blade.php add flowing :-

@foreach($records as $class)
  <tr>
    <td>{{$class->id}}</td>
    <td>
      {{$class->name}}
    </td>
    <td>
      {{$class->image_url}}
    </td>
    <td>
      {{ $class->created_at }}
    </td>

    <td>
      <a class="btn btn-primary btn-sm " href="{{route('image_status_list')}}"> VIEW</a>
    </td>

  </tr>
@endforeach
1
  • 1
    I'm not sure how this answer is even related to the question. Commented Apr 5, 2020 at 22:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.