ItSolutionStuff.com

How to Check Table Is Exists or Not in Laravel?

By Hardik Savani • November 5, 2023
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: Laravel
Hardik Savani

Hardik Savani

I'm a full-stack developer, entrepreneur, and founder of ItSolutionStuff.com. Passionate about PHP, Laravel, JavaScript, and helping developers grow.

📺 Subscribe on YouTube

We Are Recommending You

Laravel Migration Add Column After Column Example

Read Now →

Laravel Migration Default Value Current Timestamp Example

Read Now →

How to Run Migration and Seeder on Laravel Vapor?

Read Now →

How to Change Column Length using Laravel Migration?

Read Now →

How to Update Enum Value in Laravel Migration?

Read Now →

Laravel Migration Enum Default Value Example

Read Now →

How to add Default Value of Column in Laravel Migration?

Read Now →

Laravel Migration Custom Index Name Example

Read Now →

How to Add Foreign Key in Laravel Migration?

Read Now →

Laravel Migration - How to Add New Column in Existing Table ?

Read Now →

How to Change Table Name using Laravel Migration?

Read Now →

How to Remove Column from Table in Laravel Migration?

Read Now →

How to Change Column Name and Data Type in Laravel Migration?

Read Now →

How to Create Table using Migration in Laravel?

Read Now →