Transform Column Types in Laravel with Migrations

How to Add , Change , Drop column using migration in Laravel

Add | Drop | Change column type using migration - Laravel

In this article we will learn how can you add a new column , drop a column and change column datatype using migration in Laravel .

Add new column in Table :

To add a new column using migration , first create a new migration using the following command .

php artisan make:migration add_quantity_to_products_table --table=products

Add your columns , you want to add on your table .

public function up()
    {
        Schema::table('products', function (Blueprint $table) {
            $table->bigInteger('quantity');
        });
    }

Then simply run the migrate command as below .

php artisan migrate

Drop Column using Migrate :

To drop a column using migration , first create a migration file as follows .

php artisan make:migration drop_quantity_from_products --table=products

On up() method inside the migration file write the code to drop the column and inside the down() method write the existing structure of the column you want to drop as shown below .

public function up()
    {
        Schema::table('products', function (Blueprint $table) {
            $table->dropColumn('quantity');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('products', function (Blueprint $table) {
            $table->bigInteger('quantity');
        });
    }

Now simply run the migration command as below .

php artisan migrate

Alter column type :

To alter a column datatype or changing it to any default value , first create a migration file using the following command .

php artisan make:migration change_quantity_column_datatype_from_products --table=products

Now simply write your structure of your column inside up() method of the migration file with change() method  as shown below .

 public function up()
    {
        Schema::table('products', function (Blueprint $table) {
             $table->integer('quantity')->default(1)->change();
        });
    }

That's it , now simply run the migration command as shown below .

php artisan migrate



Previous Post Next Post

Contact Form