How to check existence of a table in Laravel database?

Many times during application development, we need to check existence of a table, if it exists and then pass a command or operation accordingly.

Laravel provides database migrations using Schema façade. It has several methods like add a column, remove a column, check if table exists, check if column exists, and many more supported functions. In this tutorial let us have a look at the hasTable function by the Laravel Schema Façade to check if a specific table exists in a database.

To check existence of a table in your database is compulsory for proper validation. You can easily achieve this by using Laravel’s schema builder method hasTable(). This method will accept only one argument, i.e. the name of the table to check its existence.

The code below explains the syntax and usage of this method:

if (Schema::hasTable('posts_name'))
{
    // Do something if exists
}

You may call the method in an if statement as shown above. It will check if the Laravel database Schema has the table name mentioned inside the hasTable() method. On true, it executes the code you will enclose in the brackets.

This assures that specific code blocks, most importantly, those related to the table you are checking for execute only when the table is present in the database Schema. This will avoid many exceptions like table not found when referring to data in the specific table.

Hope the code and explanation helped you check and validate your table presence for your next Laravel project!