Framework: Checking if a table exists in database.

Created on 6 Apr 2013  路  9Comments  路  Source: laravel/framework

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?

Most helpful comment

Got it:

use Illuminate\Database\Schema\Blueprint;
Schema::hasTable('projects')

All 9 comments

This should work If I'm correct.

DB::hasTable($tablename);

Nope:
[ErrorException]
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

laravel/framework/src/Illuminate/Database/Schema/Builder.php

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;
Schema::hasTable('projects')

ahh... Nice one!!! :)

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

@PhiloNL, in my case using PostgreSQL, this method hasTable() in Schema Builder presents a bug.

I try reproduce the same here, but the error Call to a member funcion compileTableExists() on null is appear in console:

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Schema\Builder as SchemaBuilder;

class MigrationUtils
{
    protected static function getConnection()
    {
        $pdo = env('DB_CONNECTION');
        $database = env('DB_DATABASE');
        return new \Illuminate\Database\Connection($pdo, $database);
    }

    public static function hasTable($table)
    {
        $schemaBuilder = new SchemaBuilder(self::getConnection());
        $connection = $schemaBuilder->getConnection();
        $schemaGrammar = $connection->getSchemaGrammar();

        return count($connection->select(
                $schemaGrammar->compileTableExists(), [$table]
            )) > 0;
    }

Please, can you help me with this specific case?

The hasTable() method does not work when the table is in a different database.

Is the same database. The collection that is different.
So. I don't use Laravel anymore.
Thanks a lot! ;)

After all, app\Eloquent\Schema::hasTable() not work!!
"shakahl/laravel-eloquent-mysqli": "dev-master",

Was this page helpful?
0 / 5 - 0 ratings