Ehsan Zargar Ershadi
Ehsan Zargar Ershadi

Reputation: 24833

Is there any way to detect if a database table exists with Laravel

I want to be able to create a table using

Schema::create('mytable',function($table)
{
    $table->increments('id');
    $table->string('title');
});

But before that I would like to check if the table already exists, perhaps something like

Schema::exists('mytable');

However, the above function does not exist. What else can I use?

Upvotes: 137

Views: 142559

Answers (7)

Syamlal
Syamlal

Reputation: 901

if (!Schema::hasTable('table_name')) {
 enter code here
}

Still working on Laravel 10

Upvotes: 0

guyaloni
guyaloni

Reputation: 5862

As Phill Sparks answered, you can check whether a table exists using:

Schema::hasTable('mytable')

Notice that there are cases your app uses different connections. In this case, you should use:

Schema::connection('myConnection')->hasTable('mytable')

(Don't forget to use use Schema; on the beginning of your code).

Upvotes: 11

pankaj
pankaj

Reputation: 1906

if you are using different connection then you have to go with my answer.

Schema::connection("bio_db")->hasTable('deviceLogs_11_2019')

here on hasTable() function you can pass more than 1 table name.

Upvotes: 6

Bimal Poudel
Bimal Poudel

Reputation: 1234

Rather, depend on information schema query instead of checking for some data in the tables with COUNT().

SELECT table_schema 
FROM information_schema.tables
WHERE table_schema = DATABASE()
      AND table_name = 'table_name';

Change your 'table_name' value.

If you get one row output, it means the table exists.

Upvotes: 1

Brn.Rajoriya
Brn.Rajoriya

Reputation: 1544

To create a new table there is only one check by Laravel Schema function hasTable.

if (!Schema::hasTable('table_name')) {
    // Code to create table
}

But if you want to drop any table before checking its existence then Schema have a function called dropIfExists.

Schema::dropIfExists('table_name');

It will drop the table if table will exist.

Upvotes: 34

Phill Sparks
Phill Sparks

Reputation: 20879

If you are using Laravel 4 or 5 then there is the hasTable() method, you can find it in the L4 source code or the L5 docs:

Schema::hasTable('mytable');

Upvotes: 312

mckendricks
mckendricks

Reputation: 377

No built in function for this in L3. You can do a raw query:

$table = "foo";
$check = DB::only('SELECT COUNT(*) as `exists`
    FROM information_schema.tables
    WHERE table_name IN (?)
    AND table_schema = database()',$table);
if(!$check) // No table found, safe to create it.
{
    // Schema::create …
}

Upvotes: 4

Related Questions