Checking if a table exists in database. #846

villimagg opened this Issue Apr 6, 2013 · 5 comments

2 participants


In Laravel 3.2 I could do this to check if a specific table existed in the database:

    // Get the connection type (production/development/mysql/sqlite???)
    $default     = Config::get('database.default');

    // Get the available db connections
    $connections = Config::get('database.connections');

    // Get the database name
    $database    = $connections[$default]['database'];

    // Create a string representation of the key in our $tables Object array
    $dbObject    = "tables_in_{$database}";

    // Type cast the string to a Scalar type
    $dbObject    = (object) $dbObject;

    // Get a handle on the key (the $table array key)
    $obj         = $dbObject->scalar;

    // Get an Object containing all the tables in our database
    $tables      = DB::query('SHOW TABLES');

    foreach($tables as $key => $val) {

    $tableName  = $val->$obj;
    $tablesArray = DB::table($tableName)->get();

    if ($tableName == 'some_aswesome_table_name') {
            // Do whatever!

Now I know that in L4 we have the awesome DB::getDatabaseName() method which simplifies it a whole lot when getting the database name but I don't see any way to run the "SHOW TABLES" sql command to retrieve an object or whatever of the database to parse and check if a specific table name exists.

How would you do that, or could we expect a method which helps with issues like these?


This should work If I'm correct.



Warning: call_user_func_array() expects parameter 1 to be a valid callback, class 'Illuminate\Database\MySqlConnection' does not have a method 'hasTable' in /home/vilhjalmur/sites/l4updates/bootstrap/compiled

.php line 10071



Seems to have the method you are looking for, but I'm not sure how to use it:

     * Determine if the given table exists.
     * @param  string  $table
     * @return bool
    public function hasTable($table)
        $sql = $this->grammar->compileTableExists();

        $table = $this->connection->getTablePrefix().$table;

        return count($this->connection->select($sql, array($table))) > 0;

Got it:

use Illuminate\Database\Schema\Blueprint;

ahh... Nice one!!! :)

Thanks. Of course there was a method for it in L4 ;)

@villimagg villimagg closed this Apr 6, 2013
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment