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

Laravel - How to Check Column Exists or Not in Table

In this article, You will learn How to check Column exists or not in a table using Laravel.


Smit Pipaliya - Author - TechvBlogs
Smit Pipaliya
 

4 months ago

TechvBlogs - Google News

Let's explore a tutorial on how to check if a column exists in Laravel and subsequently drop the column if it does. I'll guide you through an example of dropping a column in Laravel. This example will help you understand the concept of checking for the existence of a column in a table. Without further ado, let's dive into the steps.

When working on my Laravel application, I encountered a situation where I needed to remove a column from the database. However, I was uncertain whether the column existed in the tables. Fortunately, Laravel's Database Migration Schema provides a solution. By using the hasColumn method, you can check if a column exists in a table. If you also need to remove the column conditionally based on its existence, you can refer to the example below.

Laravel - How to Check Column Exists or Not in Table

Here's an example.

Create Migration:

You can effortlessly generate a migration for a database table by using the command below.

php artisan make:migration update_subscription_table

Upon executing the aforementioned command, a new file will be generated. In this file, you can add new columns with various data types such as string, integer, timestamp, and text.

database/migrations/2023_12_14_325632_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->string('stripe_id');
            });
        }
    }
  
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        if (Schema::hasColumn('subscriptions', 'stripe_id')) {
            Schema::table('subscriptions', function ($table) {
                $table->dropColumn('stripe_id');
            });
        }
    }
};

Run Migration:

The command below allows us to execute our migration, subsequently creating the specified database table.

php artisan migrate

Thank you for reading this guide!

 

Comments (0)

Comment


Note: All Input Fields are required.