How to Check Table Is Exists or Not in Laravel?

By Hardik Savani November 5, 2023 Category : Laravel

Hello Developer,

This article will give you an example of How to check table is exists or not in laravel?. I explained simply about laravel check table exists or not. This post will give you a simple example of laravel schema check if table exists. you will learn laravel migration check if table exists. Let's get started with laravel migration check if table exists.

In Laravel, you can check if a table exists in the database using the Schema::hasTable() method. This method checks whether the specified table name exists in the current database connection.

Here's an example code snippet:

Example 1:

use Illuminate\Support\Facades\Schema;

$tableName = 'users';

if (Schema::hasTable($tableName)) {

echo "Table $tableName exists";

}

Example 2: with Migration Code

<?php

use Illuminate\Database\Migrations\Migration;

use Illuminate\Database\Schema\Blueprint;

use Illuminate\Support\Facades\Schema;

return new class extends Migration

{

/**

* Run the migrations.

*/

public function up(): void

{

if (Schema::hasTable("users")) {

echo "Table users exists";

}

}

/**

* Reverse the migrations.

*/

public function down(): void

{

Schema::dropIfExists('users');

}

};

In this example, the Schema::hasTable() method is used to check if the users table exists in the database. If the table exists, the message "Table users exists" will be displayed, otherwise the message "Table users does not exist" will be displayed.

Note that you need to include the use Illuminate\Support\Facades\Schema; statement at the top of your PHP file to access the Schema facade.

I hope it can help you...

Tags :
Shares