How to fetch count of all tables available in a database
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 count of total tables available in your connected database in Laravel.
Quick solution :-
Following is an example through which you can get count of total tables available in a database in Laravel.
count(DB::select('SHOW TABLES'));
OR
count(DB::select("SELECT table_name FROM information_schema.tables WHERE table_schema = '{$database_name}'"));
Method - 1 :-
Following is an example through which you can get count of total tables available in a database 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 getTableCount(){ try{ $table_count = count(DB::select('SHOW TABLES')); return $table_count; } 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 getTableCount(){ try{ $database_name = "devtrigger"; $table_count = count(DB::select("SELECT table_name FROM information_schema.tables WHERE table_schema = '{$database_name}'")); return $table_count; } catch(\Exception $e){ return false; } } }
Thank you for reading this article 😊
For any query do not hesitate to comment 💬