Laravel - How to Check Column Exists or Not in Table?
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, laravel 9, laravel 10 and laravel 11 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...
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 Enum Default Value Example
- Laravel Migration Add Enum Column Example
- How to Rollback Migration in Laravel?
- Laravel Migration Add Comment to Column Example
- How to add Default Value of Column in Laravel Migration?
- Laravel Migration Custom Index Name Example
- Laravel Migration Custom Foreign Key Name Example
- How to Add Index in Laravel Migration?
- 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?