Struggling with Laravel Database Tables? Here's Your Solution!

 How to get list of table names from database in Laravel

Struggling-with-Laravel-Database-Tables-Here's-Your-Solution

Laravel provides lots of query methods, functions to solve of our all kind of database related requirements whether it using eloquent query or using the query builder methods. In this articles will see different ways to get list of table names available in your connected database in Laravel.

Quick solution :-

You can use the following any of the code to get list of table names from database in Laravel. Both the codes below will return you list of objects with table names.

DB::select("SELECT table_name FROM information_schema.tables WHERE table_schema = '{$database_name}'");

OR

DB::select('SHOW TABLES');


Method - 1 :-

Following is an example through which you can get list of table names in the form of array in Laravel.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Schema;
use DB;

class HomeController extends Controller
{
    public function getTableNames(){
      try{
        $database_name = "devtrigger";
        $tables = DB::select("SELECT table_name FROM information_schema.tables WHERE table_schema = '{$database_name}'");
        foreach($tables as $key => $table){
            $table_names[] = $table->table_name;
        }
        return $table_names;
      }
      catch(\Exception $e){
        return false;
      }
    }
}


Method - 2 :-

Following is an example through which you can get list of table names in the form of array in Laravel.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Schema;
use DB;

class HomeController extends Controller
{
    public function getTableNames(){
        try{
          $tables = DB::select('SHOW TABLES');
          foreach($tables as $key => $table){
              $table_names[] = $table->Tables_in_devtrigger; // Table_in_{{your database name in my case database name is devtrigger}}
          }
          return $table_names;
        }
        catch(\Exception $e){
          return false;
        }
      }
}

Output :-

Get list of tables from a Database in Laravel [SOLVED]

Previous Post Next Post

Contact Form