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

PhpLaravel

Php Problem Overview


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?

Php Solutions


Solution 1 - Php

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');

Solution 2 - Php

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.

Solution 3 - Php

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).

Solution 4 - Php

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.

Solution 5 - Php

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 …
}

Solution 6 - Php

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionEhsan Zargar ErshadiView Question on Stackoverflow
Solution 1 - PhpPhill SparksView Answer on Stackoverflow
Solution 2 - PhpBrn.RajoriyaView Answer on Stackoverflow
Solution 3 - PhpguyaloniView Answer on Stackoverflow
Solution 4 - Phppankaj kumarView Answer on Stackoverflow
Solution 5 - PhpmckendricksView Answer on Stackoverflow
Solution 6 - PhpBimal PoudelView Answer on Stackoverflow