How to Check Table Is Exists or Not in 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...
Hardik Savani
I'm a full-stack developer, entrepreneur and owner of ItSolutionstuff.com. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.
We are Recommending you
- Laravel Migration Add Column After Column Example
- Laravel Migration Default Value Current Timestamp Example
- How to Run Migration and Seeder on Laravel Vapor?
- How to Change Column Length using Laravel Migration?
- How to Update Enum Value in Laravel Migration?
- Laravel Migration Enum Default Value Example
- How to add Default Value of Column in Laravel Migration?
- Laravel Migration Custom Index Name Example
- How to Add Foreign Key in Laravel Migration?
- Laravel Migration - How to Add New Column in Existing Table ?
- How to Change Table Name using Laravel Migration?
- How to Remove Column from Table in Laravel Migration?
- How to Change Column Name and Data Type in Laravel Migration?
- How to Create Table using Migration in Laravel?