How To Check If a Database Table Exists With Laravel

Reading Time: 2 minutes
825 Views

Inside this article we will see the concept i.e How To Check If a Database Table Exists With Laravel. Article contains the classified information about Checking if a table exists in database using Laravel schema concept.

Whenever you create a new table schema inside your database, you first need to check if table already exists. If not, then you will proceed with new table schema creation.

So, If you don’t have this idea then this tutorial will be helpful for you for this. Tutorial is super easy to understand and implement it in your code as well.

This article is not for any laravel version specific. You can use this concept with Laravel v6, Laravel v7, Laravel v8 also.

Read More: How To Add JQuery Ajax Loading Spinner in Laravel Example

Let’s get started.

Laravel Installation

Open terminal and run this command to create a laravel project.

composer create-project laravel/laravel myblog

It will create a project folder with name myblog inside your local system.

To start the development server of laravel –

php artisan serve

URL: http://127.0.0.1:8000

Assuming laravel already installed inside your system.

How To Check Table Existence in Database

We will use Schema facade for this.

To check database table existence, you can easily achieve this by using one of Laravel’s schema builder method hasTable(). The Laravel schema builder hasTable() method accepts one argument i.e the name of the table.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Schema;

class HomeController extends Controller
{
    public function index()
    {
        if (Schema::hasTable('table_name')) {

            dd('Table Exists...');
        }
    }
}

Concept

Schema::hasTable(‘table_name’) returns True when table exists else it will return False boolean value.

Read More: How To Get File Name From a Path in PHP Example

We hope this article helped you to learn How To Check If a Database Table Exists With Laravel in a very detailed way.

Online Web Tutor invites you to try Skillshike! Learn CakePHP, Laravel, CodeIgniter, Node Js, MySQL, Authentication, RESTful Web Services, etc into a depth level. Master the Coding Skills to Become an Expert in PHP Web Development. So, Search your favourite course and enroll now.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.

Sanjay KumarHello friends, I am Sanjay Kumar a Web Developer by profession. Additionally I'm also a Blogger, Youtuber by Passion. I founded Online Web Tutor and Skillshike platforms. By using these platforms I am sharing the valuable knowledge of Programming, Tips and Tricks, Programming Standards and more what I have with you all. Read more