How to Check Database Table Exists or Not in Laravel?

Sovary January 12, 2023 370
1 minute read

If you want to build an web app for user to install just like wordpress only click on UI you may want to check the existing table in you database, or before doing something else with the table. You can check by using schema builder method hasTable() which is accepted table's name as argument.

You can use this example with the versions of laravel 6, laravel 7, laravel 8, and laravel 9.

Step 1 - Install Laravel App

Please skip this step if you have installed Laravel, if not then you have to run below command to dowload Laravel project.

composer create-project laravel/laravel blog

By default in Laravel have a controller named HomeController.php

Step 2 - Checking Table in Controller

Open file App/Http/Controllers/HomeController.php

<?php
  
namespace App\Http\Controllers;
   
class HomeController extends Controller
{

    public function index()
    {
        if (Schema::hasTable('your_table'))
        {
            // Do some code here
            print("Yes existing table");
        }
    }
}

Output:

Yes existing table

Hope this short article help you to check table in database. Have a nice day!!

You might also like...

Laravel  PHP 
Author

Founder of CamboTutorial.com, I am happy to share my knowledge related to programming that can help other people. I love write tutorial related to PHP, Laravel, Python, Java, Android Developement, all published post are make simple and easy to understand for beginner. Follow him