iGenezys's avatar

Show Databases in Laravel

Hello world.

I wanted to try something like displaying all my tables in my database in a Laravel app. After searching for the web I found nothing good, and i'm blocked at the very beginning, the mysql connection.

As you see in the config file and the .env, we need to have a database name setup on the app

'mysql' => [
            'driver' => 'mysql',
            'url' => env('DATABASE_URL'),
            'host' => env('DB_HOST', '127.0.0.1'),
            'port' => env('DB_PORT', '3306'),
            'database' => '',
            'username' => env('DB_USERNAME', 'forge'),
            'password' => env('DB_PASSWORD', ''),
            'unix_socket' => env('DB_SOCKET', ''),
            'charset' => 'utf8mb4',
            'collation' => 'utf8mb4_unicode_ci',
            'prefix' => '',
            'prefix_indexes' => true,
            'strict' => true,
            'engine' => null,
            'options' => extension_loaded('pdo_mysql') ? array_filter([
                PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
            ]) : [],
        ],

I tried to remove the database attribute but when I do this code for the test

$db = DB::connection();

        $db->query('SHOW DATABASES');

        dd($db);

It return an error because I don't have any database setup.

I saw in Internet that I need to setup a whole config table for each table, but at the moment I have like 15-20 tables, that's gonna be kinda big, and I wanted it to be automatic.

So how could I do my "Show databases" request on a Laravel app ?

Thank you !

0 likes
11 replies
Sinnbeck's avatar

I assume you mean to show the tables not the databases

$tables = DB::select('SHOW TABLES');
foreach($tables as $table)
{
      $tableNames[] = $table->Tables_in_db_name;
}
dd($tableNames);
iGenezys's avatar

Not here, that's the point, I wanted to know if the "Show Databases" that I did on MySQL can be done on a Laravel App

I'd like to post an Image but seems I can't here

All the tutorials that I wanted to find show how to display tables, not the databases.

Sinnbeck's avatar

You can just post it to imgur.com and post the link

Does the database user have access to all databases?

jlrdw's avatar

@igenezys just right click, view image, get url, and put in an image tag here, a regular image tag.

sauravs012's avatar

this will return all the databases

$tables = \DB::select('SHOW DATABASES');
dd($tables);
1 like
Sinnbeck's avatar
Sinnbeck
Best Answer
Level 102

Set a default database in the config. Then run the SHOW DATABASES and make a nested loop to get the tables for each (set the database using config()

$tableNames = [];
foreach (\DB::select('SHOW DATABASES') as $database) {
    config('database.connections.mysql.database', $database->Database);
    $tables = \DB::select('SHOW TABLES');
     foreach($tables as $table) {
        $tableNames[$database->Database][] = $table->Tables_in_db_name;
    }
    
}
dd($tableNames);
1 like
thewebartisan7's avatar

In config/database.php add multiple connections, one for each database, and you can add name for each that corrispond to your database name. For example:


// default
        'mysql' => [
            'driver' => 'mysql',
            'url' => env('DATABASE_URL'),
            'host' => env('DB_HOST', '127.0.0.1'),
            'port' => env('DB_PORT', '3306'),
            'database' => env('DB_DATABASE', 'forge'),
            'username' => env('DB_USERNAME', 'forge'),
            'password' => env('DB_PASSWORD', ''),
            'unix_socket' => env('DB_SOCKET', ''),
            'charset' => 'utf8mb4',
            'collation' => 'utf8mb4_unicode_ci',
            'prefix' => '',
            'prefix_indexes' => true,
            'strict' => true,
            'engine' => null,
            'options' => extension_loaded('pdo_mysql') ? array_filter([
                PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
            ]) : [],
        ],

// Another database
        'database_name' => [
            'driver' => 'mysql',
            'url' => env('DATABASE_URL'),
            'host' => env('DB_HOST', '127.0.0.1'),
            'port' => env('DB_PORT', '3306'),
            'database' => 'database_name', // change database name
            'username' => env('DB_USERNAME', 'forge'),
            'password' => env('DB_PASSWORD', ''),
            'unix_socket' => env('DB_SOCKET', ''),
            'charset' => 'utf8mb4',
            'collation' => 'utf8mb4_unicode_ci',
            'prefix' => '',
            'prefix_indexes' => true,
            'strict' => true,
            'engine' => null,
            'options' => extension_loaded('pdo_mysql') ? array_filter([
                PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
            ]) : [],
        ],

// ...etc...

Then somewhere in your php code do something like:



// Using default connection to get all databases
$databases = array_map('reset', \DB::select('SHOW DATABASES'));

// Get first all tables of default connection
$data['default'] = array_map('reset', \DB::select('SHOW TABLES'));

// Loop over databases
foreach($databases as $database) {

// Get all tables of the new connection, maybe add check if you want to skip some database
 $data[$database] = array_map('reset', \DB::connection($database)->select('SHOW TABLES'));
}


dd($data);

If you need also to show fields of each table, add in the loop something like:


 foreach($data[$database] as $key => $table) {
   $data[$database][$table] = \DB::select(\DB::raw("SHOW FIELDS FROM $table"));
}

I didn't test, but it should works.

Hope it helps.

iGenezys's avatar

All the replies helps, thanks a lot ! The major problem here was that I needed to set up a default database, then I can use @sauravs012 or @sinnbeck response for getting my databases

From here I can move on the next phase, and @sinnbeck & @zoroaster reps show me a way to do it.

Thanks again !

qylidavug's avatar
    $tableNames = [];
    foreach (FacadesDB::select('SHOW DATABASES') as $database) {
        config('database.connections.mysql.database', $database->Database);
        $tables = FacadesDB::select('SHOW TABLES');
        foreach ($tables as $table) {
            foreach ($table as $item) {
                $tableNames[$database->Database][] = $item;
            }
        }

    }
    dd($tableNames);
Loki9's avatar

If you are using Laravel with MongoDB, you can use below code to get names of all the collections in the database:

$collections = DB::connection('mongodb')->getMongoDB()->listCollections();

For more details, you can look through the official documentation.

Please or to participate in this conversation.