Laravel - How to Check Column Exists or Not in Table?

By Hardik Savani July 7, 2022 Category : Laravel

Now, let's see tutorial of laravel check column exists. I would like to show you laravel drop column if exists. we will help you to give example of laravel drop column example. you can understand a concept of check if column exists in table laravel. Alright, let’s dive into the steps.

you can use this example with laravel 6, laravel 7, laravel 8 and laravel 9 version.

When i was working my laravel application at that time i need to remove column from database. But i am not sure that column is exists or not in tables. So i was thinking, but i found solution from Laravel Database Migration Schema. we can check column is exists or not in tables using hasColumn. If you also need to remove if column is exists then you can use bellow example.

I will give you full example, let's see below example:

Create Migration:

Using bellow command you can simply create migration for database table.

php artisan make:migration update_subscription_table

After run above command, you can see created new file as bellow and you have to add new column for string, integer, timestamp and text data type as like bellow:

database/migrations/2022_02_17_133331_update_subscription_table.php

<?php

use Illuminate\Database\Migrations\Migration;

use Illuminate\Database\Schema\Blueprint;

use Illuminate\Support\Facades\Schema;

return new class extends Migration

{

/**

* Run the migrations.

*

* @return void

*/

public function up()

{

if (Schema::hasColumn('subscriptions', 'stripe_id')) {

Schema::table('subscriptions', function ($table) {

$table->dropColumn('stripe_id');

});

}

}

/**

* Reverse the migrations.

*

* @return void

*/

public function down()

{

Schema::dropIfExists('posts');

}

};

Run Migration:

Using bellow command we can run our migration and create database table.

php artisan migrate

I hope it can help you...