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);
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 !
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);
Please or to participate in this conversation.